Live Archipelago Counter with Incremental Land Reclamation
Trees & GraphsAuto-graded · 18 test casesLast updated
Count 4-connected land regions in a grid, then report the updated region count after each cell is converted from water to land, using incremental connectivity.
Live Archipelago Counter with Incremental Land Reclamation
You are given a map of a sea as a rectangular grid. A cell holding 0 is water and a cell holding 1 is land. Two land cells are part of the same island if you can travel between them by stepping only onto land cells, moving one step up, down, left, or right each time (diagonal steps do not count).
You are also given a list of reclamation orders. Each order is a pair [row, col] naming a cell. Orders are applied one at a time, in the given sequence:
- If the named cell is water, it becomes land.
- If the named cell is already land (either originally or from an earlier order), nothing changes.
Your task is to produce a list of island counts:
- The first entry is the number of islands in the original grid, before any order is applied.
- After each order is processed, append the number of islands currently on the map (even if that order changed nothing).
The returned list therefore has length len(additions) + 1.
The input grid and the list of orders must not be modified.
Constraints
- The grid has at least one row and at least one column.
- All rows have the same length, and the grid has at most 200,000 cells in total.
0 <= len(additions) <= 200,000.- Each order consists of two integers that identify a valid cell in the grid.
- Aim for roughly
O(R*C + A*alpha(R*C))time andO(R*C)extra space, whereR*Cis the number of cells andAis the number of orders.
Examples
Example 1
Input: count_islands_over_time([[1, 0, 0], [0, 0, 1]], [[0, 1], [1, 1], [1, 1]])
Output: [2, 2, 1, 1]
Example 2
Input: count_islands_over_time([[0, 0]], [[0, 0], [0, 1]])
Output: [0, 1, 1]
Hints
Hint 1
Recomputing the island count from scratch after every order costs O(R*C) each time, which is far too slow at the largest sizes. Think about what a single new land cell can actually change.
Hint 2
A new land cell starts as its own island, then merges with each distinct neighboring island. Two neighbors might already be in the same island, so merging must only reduce the count when two different islands are joined.
Hint 3
Use a disjoint-set union (union-find) over flattened cell indices. Have union report whether it joined two different sets, and only then reduce the count. Skip orders that target cells that are already land.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Flatten each cell (r, c) to the index r * cols + c and keep a union-find (disjoint-set) structure over the land cells. A cell that is still water is marked as "absent" (parent -1).
Initial state. Every land cell starts as its own set and adds 1 to the island count. Then, for each land cell, union it with its land neighbor to the right and the one below. Looking only right and down covers every adjacent pair exactly once. Each union that joins two different sets lowers the count by 1. After this pass, the sets are exactly the islands.
Processing an order. For [r, c]:
- If the cell is already land, nothing changes. Append the current count.
- Otherwise, make it a new singleton set and add 1 to the count. Then try to union it with each of its (up to four) land neighbors. A union lowers the count only if the two roots differ, so a neighbor that is already in the same island as another neighbor does not cause a double decrement. Append the count.
Why it is correct
The invariant is that after each step the union-find sets correspond exactly to the islands, and the counter equals the number of sets. Initially this holds because we union every adjacent land pair. When water becomes land, any new connectivity must pass through the new cell, so connecting it to its land neighbors captures every merge. Cells never revert to water, so islands only merge and never split, which is exactly what union-find supports. Duplicate or already-land orders are skipped explicitly, so they leave the count unchanged.
Recomputing with a full scan after every order would cost O(A * R*C), which is far too slow; the local update avoids it.
Complexity
- Time:
O(R*C + A * alpha(R*C)), since each order performs at most four unions with union by size and path compression. - Space:
O(R*C)for the parent and size arrays (plus the required output).
Reference solution
from typing import List
def count_islands_over_time(grid: List[List[int]], additions: List[List[int]]) -> List[int]:
rows = len(grid)
cols = len(grid[0])
n = rows * cols
parent = [-1] * n
size = [0] * n
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
idx = r * cols + c
parent[idx] = idx
size[idx] = 1
islands += 1
def find(x):
root = x
while parent[root] != root:
root = parent[root]
while x != root:
nxt = parent[x]
parent[x] = root
x = nxt
return root
def union(a, b):
nonlocal islands
ra = find(a)
rb = find(b)
if ra == rb:
return
if size[ra] < size[rb]:
ra, rb = rb, ra
parent[rb] = ra
size[ra] += size[rb]
islands -= 1
for r in range(rows):
for c in range(cols):
idx = r * cols + c
if parent[idx] == -1:
continue
if c + 1 < cols and parent[idx + 1] != -1:
union(idx, idx + 1)
if r + 1 < rows and parent[idx + cols] != -1:
union(idx, idx + cols)
counts = [islands]
for r, c in additions:
idx = r * cols + c
if parent[idx] == -1:
parent[idx] = idx
size[idx] = 1
islands += 1
if r > 0 and parent[idx - cols] != -1:
union(idx, idx - cols)
if r + 1 < rows and parent[idx + cols] != -1:
union(idx, idx + cols)
if c > 0 and parent[idx - 1] != -1:
union(idx, idx - 1)
if c + 1 < cols and parent[idx + 1] != -1:
union(idx, idx + 1)
counts.append(islands)
return counts