← Questions

Largest island perimeter in a grid

0

A coding interview question asked at Google and Tesla. It tests graphs, bfs and grid.

You are given an m x n grid where each cell is either land ("1") or water ("0"). Land cells that touch horizontally or vertically (not diagonally) belong to the same island.

Treat every land cell as a unit square with four sides. A side is part of its island's perimeter when the cell on the other side is water or lies outside the grid. Water enclosed by an island counts as water, so its edges are part of the perimeter too.

Implement:

def max_island_perimeter(grid: list[list[str]]) -> int: ...

Return the largest perimeter of any island in the grid, or 0 if there is no land. The island with the most cells does not always have the largest perimeter.

Constraints

  • 0 <= m, n <= 1000
  • grid[i][j] is "0" or "1"
  • Your solution should run in time linear in the number of cells and must not depend on deep recursion.

Example 1

grid = [
  ["1","1","0","0"],
  ["1","1","0","1"],
  ["0","0","0","1"],
  ["1","1","1","1"],
]

Output: 14. The top-left 2x2 block has perimeter 8. The six cells on the right and bottom form one L-shaped island with perimeter 14.

Example 2

grid = [
  ["1","1","1"],
  ["1","0","1"],
  ["1","1","1"],
]

Output: 16. The ring has 12 outer edges plus 4 edges facing the enclosed water.

Be ready to extend your solution, for example to land that is added one cell at a time.

Clarifying questions

  • Do the edges facing an enclosed lake count? (Yes, per Example 2.)
  • Are diagonal cells part of the same island? (No.)
  • Can the grid be empty or ragged?
  • Do we need which island it is, or only the perimeter?

What a strong answer covers

  • Labels each island with an iterative BFS or DFS, or with union-find. Recursion is not safe on a 1000 x 1000 grid.
  • For each land cell, adds 4 minus its number of land neighbours to its island's total. That is the same as counting sides that face water or the edge of the grid.
  • Keeps the largest total. That is O(m x n) time and O(m x n) memory in the worst case for the queue and the visited marks.
  • Explains why the largest island by area need not have the largest perimeter (a long thin island beats a square).
  • Tests an empty grid, all water, all land (2(m + n)), the ring in Example 2, and single cells.

Follow-ups

  • Land is added one cell at a time, with the answer after each: union-find that also tracks each island's perimeter.
  • Count only the outer coastline, without the edges of enclosed lakes.
  • Islands also connect diagonally.
  • The grid is too large for memory and arrives row by row.

Where it's asked

What it tests

graphs · bfs · grid · union-find

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding