Island areas and water boundaries

0
Sign in

You are given an m x n grid of characters. Each cell is '1' (land) or '0' (water). Land cells that share a side (up, down, left or right) belong to the same island. Diagonal cells are not connected.

For every island, report two numbers:

  • Area: how many land cells the island has.
  • Water boundary: how many cell sides of the island touch water. Treat everything outside the grid as water, so a land side on the edge of the map counts. A side shared by two land cells of the island does not count.

Implement island_stats(grid) -> list[tuple[int, int]], returning one (area, boundary) pair per island. List islands in the order a row-by-row, left-to-right scan first reaches them. The number of islands is the length of the result.

Constraints

  • 0 <= m, n <= 1000
  • Each cell is '0' or '1'.
  • Aim for O(m * n) time. Your solution must not fail on a grid that is entirely land.

Example 1

grid = ["1100",
        "1001",
        "0011"]

Output: [(3, 8), (3, 8)]. The top-left island has 3 cells and 8 sides that face water or the map edge. The bottom-right island also has 3 cells and 8 such sides.

Example 2

grid = ["111",
        "101",
        "111"]

Output: [(8, 16)]. The ring has 12 sides on the outside and 4 sides around the water cell in the middle.

Reconstructed from the reported question; details may differ from what interviewers ask.

WaymoCodingMedium

Sign in to see the worked answer

The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.