Taro Logo

Island Perimeter

#6 Most AskedEasy
Topics:
Arrays

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.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the maximum dimensions (`rows` and `cols`) of the grid, and what should I expect if the grid is empty or has a null input?
  2. Is it guaranteed that there is always exactly one continuous island, or could there be multiple disconnected land masses or even zero land cells?
  3. Can the grid be composed entirely of water (no `1`s), and if so, what should the expected perimeter return value be (e.g., 0)?
  4. Are the grid cells guaranteed to form a simple polygon without any internal 'lakes' or enclosed bodies of water, or can the island have holes inside it?
  5. Should I handle the grid as a mutable structure where I can modify cells in place, or is it strictly expected to be treated as read-only?

Brute Force Solution

Approach

To find the total perimeter of an island on a grid, the brute force approach inspects every single square one by one. For each land square we find, we thoroughly check its immediate neighbors in all four directions to count how many edges are exposed to the water or the edge of the board.

Here's how the algorithm would work step-by-step:

  1. Scan across the entire grid from top to bottom, left to right, looking for land squares.
  2. Whenever you land on a square that represents land, stop and prepare to examine its four immediate neighbors: the one above, the one below, the one to the left, and the one to the right.
  3. For each of those four directions, check if the neighboring spot is water or if it falls completely off the edge of the grid.
  4. Every time you find a neighbor that is water or outside the grid, count that as one exposed edge contributing to the perimeter of the island.
  5. Add up all the exposed edges you found for that specific land square.
  6. Move on to the next square on the grid and repeat the exact same counting process.
  7. Keep a running total of all the exposed edges counted from every land square until you have checked the entire grid, which gives you the final perimeter.

Code Implementation

def islandPerimeter(grid):    total_perimeter = 0    row_count = len(grid)    column_count = len(grid[0])    # Iterate through every cell in the grid to locate all individual land squares    for row_index in range(row_count):        for col_index in range(column_count):            if grid[row_index][col_index] == 1:                                directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]                for row_offset, col_offset in directions:                    neighbor_row = row_index + row_offset                    neighbor_col = col_index + col_offset                                        # Check if neighbor is out of bounds because grid edges count as perimeter                    if neighbor_row < 0 or neighbor_row >= row_count or neighbor_col < 0 or neighbor_col >= column_count:                        total_perimeter += 1                                        # Check if neighbor is water because land borders with water contribute to perimeter                    elif grid[neighbor_row][neighbor_col] == 0:                        total_perimeter += 1    # Return the accumulated perimeter count after checking all land squares and their neighbors    return total_perimeter

Big(O) Analysis

Time Complexity
O(m * n) – To find the island perimeter, we scan across the entire grid using nested loops, where m represents the number of rows and n represents the number of columns. For every single land square encountered during this traversal, we perform a constant time check of its four immediate neighbors to count exposed edges. The total operations scale directly with the total number of cells in the grid, which is m * n, leading to a linear time complexity relative to the grid size.
Space Complexity
O(1) – The algorithm only maintains a single running total variable to accumulate the perimeter count and a few primitive loop counter variables for iterating through the grid. No additional data structures, hash maps, or recursive call stacks are utilized during the execution. Therefore, the extra memory required remains constant regardless of the grid dimensions, resulting in an optimal auxiliary space complexity.

Optimal Solution

Approach

Instead of measuring the entire grid all at once, the optimal approach simply inspects every single piece of land one by one. By checking its immediate neighbors, you can instantly determine how many outer edges that specific piece contributes to the final boundary.

Here's how the algorithm would work step-by-step:

  1. Look at the entire grid and find every single piece of land.
  2. For each piece of land you find, imagine it as a solid block with four potential sides.
  3. Check the four immediate neighboring directions: above, below, to the left, and to the right.
  4. Every time you find a neighboring direction that is water or falls completely outside the edge of the grid, count that side as contributing to the perimeter.
  5. Every time you find a neighboring direction that contains another piece of land, realize that they share an edge, meaning that side is hidden and does not count toward the perimeter.
  6. Add up all the contributing sides for every piece of land you examine.
  7. Once all pieces of land have been checked, the total count gives you the exact final perimeter without needing any complicated math.

Code Implementation

class Solution:
    def islandPerimeter(self, grid: list[list[int]]) -> int:
        total_perimeter = 0
        row_count = len(grid)
        column_count = len(grid[0])

        # We iterate through every cell to evaluate land blocks individually.
        for current_row in range(row_count):
            for current_col in range(column_count):
                if grid[current_row][current_col] == 1:
                    
                    # Each land block starts with four potential perimeter edges.
                    for row_offset, col_offset in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
                        neighbor_row = current_row + row_offset
                        neighbor_col = current_col + col_offset

                        # Out-of-bounds or water means this side is exposed to the outer edge.
                        if neighbor_row < 0 or neighbor_row >= row_count or neighbor_col < 0 or neighbor_col >= column_count:
                            total_perimeter += 1
                        elif grid[neighbor_row][neighbor_col] == 0:
                            total_perimeter += 1

        # Return the accumulated outer boundary count after checking all land pieces.
        return total_perimeter

Big(O) Analysis

Time Complexity
O(R * C) – The time complexity is driven by a nested traversal over every single cell in the grid, where R represents the number of rows and C represents the number of columns. For each piece of land encountered, we inspect its four immediate neighbors in constant time. This requires evaluating every cell once, leading to approximately R * C total operations. By simplifying this expression, we arrive at a final Big O time complexity of O(R * C), or O(n) where n is the total number of cells in the grid.
Space Complexity
O(1) – The optimal approach simply inspects every single piece of land one by one and evaluates its four immediate neighbors without using any auxiliary data structures. The algorithm only requires a few constant primitive variables to keep track of the total perimeter count and loop indices. Since no extra memory is allocated that scales with the grid dimensions, the auxiliary space remains constant regardless of the input size.

Edge Cases

Null or empty 2D grid input
How to Handle:
Check for null or zero-length grids at the beginning and return a perimeter of zero immediately.
Minimum sized grid containing a single land cell
How to Handle:
Iterate through the single cell and add 4 to the perimeter since all four of its sides are exposed to water or grid boundaries.
Grid where all cells are water
How to Handle:
Traverse the grid without finding any land cells, resulting in a final returned perimeter of zero.
Grid completely filled with land
How to Handle:
Each interior cell contributes zero to the perimeter, while boundary cells correctly account for the outer edges.
Maximum sized grid constraints
How to Handle:
Use an efficient O(rows times cols) single pass traversal to inspect each cell and its neighbors without exceeding time limits.
Island with complex shapes like hollow inner lakes or narrow corridors
How to Handle:
Checking adjacent cells for water or boundaries naturally accounts for interior perimeter contributions as well.
Memory constraints with large grid inputs
How to Handle:
Iterate directly through the provided grid in place without allocating additional major data structures, keeping space complexity at O(1).
0/33 completed