Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Island Perimeter

Updated
2 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "463" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn't have "lakes", meaning the water inside isn't connected to the water around the island. One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island. Example 1: Input: grid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]] Output: 16 Explanation: The perimeter is the 16 yellow stripes in the image above. Example 2: Input: grid = [[1]] Output: 4 Example 3: Input: grid = [[1,0]] Output: 4 Constraints: row == grid.length col == grid[i].length 1 <= row, col <= 100 grid[i][j] is 0 or 1. There is exactly one island in grid.

Explanation

Here's the solution:

  • Iterate through each cell in the grid.
  • If a cell is land (grid[i][j] == 1), check its four neighbors (up, down, left, right).
  • If a neighbor is water (0) or out of bounds, increment the perimeter.

  • Runtime Complexity: O(row * col), Storage Complexity: O(1)

Code

    class Solution:
    def islandPerimeter(self, grid: list[list[int]]) -> int:
        """
        Calculates the perimeter of the island in the given grid.

        Args:
            grid: A list of lists of integers representing the grid. 1 represents land, 0 represents water.

        Returns:
            The perimeter of the island.
        """

        perimeter = 0
        rows = len(grid)
        cols = len(grid[0])

        for i in range(rows):
            for j in range(cols):
                if grid[i][j] == 1:
                    # Check up
                    if i == 0 or grid[i - 1][j] == 0:
                        perimeter += 1
                    # Check down
                    if i == rows - 1 or grid[i + 1][j] == 0:
                        perimeter += 1
                    # Check left
                    if j == 0 or grid[i][j - 1] == 0:
                        perimeter += 1
                    # Check right
                    if j == cols - 1 or grid[i][j + 1] == 0:
                        perimeter += 1

        return perimeter

More from this blog

C

Chatmagic blog

2894 posts

Solving Leetcode Interviews in Seconds with AI: Island Perimeter