Python coding

Islands after each new land cell

A map with rows × cols cells starts as all water. Each [r, c] in cells turns that cell into land, in order. An island is a group of land cells joined up, down, left or right. Return a list with the number of islands after each addition.

The same cell may appear more than once; adding it again changes nothing. Aim for near-constant time per addition instead of recounting the whole map.

Besides the tests, one large input (a 40 × 40 map, 1,600 additions) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • islands_after_each(3, 3, [[0,0],[0,1],[1,2],[2,1]]) → [1,1,2,3]
  • islands_after_each(2, 3, [[0,0],[0,2],[0,1]]) → [1,2,1]
  • islands_after_each(1, 1, [[0,0],[0,0]]) → [1,1]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Recounting the islands after every addition costs a full flood fill each time. Union-find keeps the groups up to date as land arrives.

Hint 2

A new land cell starts as its own island: count + 1. Then look at its four neighbors: every union that joins two different roots takes one island away.

Hint 3

Two traps: a cell added twice must not count again, and two neighbors that already share a root merge only once. Compare roots before you decrement.

Solution and why it works
pythonO(R·C + k·α(R·C)), k = additions · O(R·C)
def islands_after_each(rows: int, cols: int, cells: list[list[int]]) -> list[int]:
    parent, size = [-1] * (rows * cols), [1] * (rows * cols)    # parent -1 = water

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]    # path halving
            x = parent[x]
        return x

    counts, islands = [], 0
    for r, c in cells:
        cell = r * cols + c
        if parent[cell] == -1:               # a repeated cell changes nothing
            parent[cell] = cell
            islands += 1
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if not (0 <= nr < rows and 0 <= nc < cols) or parent[nr * cols + nc] == -1:
                    continue
                a, b = find(cell), find(nr * cols + nc)
                if a != b:                   # two different islands become one
                    if size[a] < size[b]:
                        a, b = b, a
                    parent[b] = a            # smaller tree under the larger root
                    size[a] += size[b]
                    islands -= 1
        counts.append(islands)
    return counts

Each new land cell is born as its own island, and every union that joins two different roots removes one, so the count is updated in near-constant time instead of re-flooding the map. Check roots, not neighbors: a cell that touches the same island on two sides must subtract only once, and a repeated cell must not add a new island. Mapping (r, c) to r * cols + c lets plain lists hold the forest; path halving plus union by size keep find near-constant.