Number of Islands II

hard

You start with an m x n grid of water. You're given positions, where positions[i] = [r, c] turns the cell (r, c) into land. After each operation, report the number of islands (4-directionally connected land). Return an array with the island count after each operation. (Turning an already-land or out-of-range cell to land leaves the count unchanged.)

Hints

Land is only ever added, so maintain the island count incrementally.
A new land cell starts as its own island (+1).
Union it with each adjacent land cell; every merge reduces the count by one.

Common doubts

Connectivity only grows (cells turn from water to land), and union-find maintains a component count under added edges in near-O(1).
It recounts the entire grid after every add — O(P·m·n) — even though only one cell changed.
Turning an already-land cell to land changes nothing, so the count is repeated for that step.

Interview follow-ups

Union-find can't un-merge; you'd process operations in reverse or use a different structure.
Union with the diagonal neighbours too.

Fun facts

  • LeetCode 305 — the streaming version of Number of Islands, and a showcase for incremental union-find.
  • Reversing the operations turns 'remove land' problems back into this add-only pattern.

Asked at

AmazonGoogleMicrosoft
Frequently Sometimes Occasionally
Example 1
Input: m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
Output: [1, 1, 2, 3]
The second add merges with the first; the rest are new islands.
Example 2
Input: m = 1, n = 1, positions = [[0,0]]
Output: [1]
A single land cell is one island.
Constraints

- 1 <= m, n <= 10^4 - 0 <= positions.length <= 10^4 - positions[i] is [r, c]

Solve this problem →