Number of Islands II

Stream of land additions on a grid — report island count after each.

Hard
Time O(K * α(M * N)) Space O(M * N)
LeetCode
7 min read
union-find grid streaming

Problem#

Given an m x n water grid and a list of positions adding land cells one by one, return after each addition the current count of islands (4-connected land components).

Examples#

  • m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]][1,1,2,3].
  • m = 1, n = 1, positions = [[0,0]][1].

Constraints#

  • 1 <= m, n, positions.length <= 10^4.

Hints#

Hint
DSU with running count: adding a cell increments by 1, unioning with each new neighbor decrements by 1.

Approach#

Initialize DSU and count = 0. For each position: if already land, skip with current count. Otherwise mark land, count++, and union with each of the 4 land neighbors (each successful union decrements count).

Solution#

Number of Islands II
class Solution {
vector<int> parent, rnk;
int find(int x) { while (parent[x] != x) { parent[x] = parent[parent[x]]; x = parent[x]; } return x; }
bool unite(int a, int b) {
a = find(a); b = find(b); if (a == b) return false;
if (rnk[a] < rnk[b]) swap(a, b);
parent[b] = a; if (rnk[a] == rnk[b]) ++rnk[a];
return true;
}
public:
vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
parent.assign(m * n, -1); rnk.assign(m * n, 0);
vector<int> ans;
ans.reserve(positions.size());
int count = 0;
static const int dr[4] = {-1, 1, 0, 0}, dc[4] = {0, 0, -1, 1};
for (auto& p : positions) {
int r = p[0], c = p[1], u = r * n + c;
if (parent[u] != -1) { ans.push_back(count); continue; }
parent[u] = u;
++count;
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
int v = nr * n + nc;
if (parent[v] != -1 && unite(u, v)) --count;
}
ans.push_back(count);
}
return ans;
}
};

Editorial#

DSU naturally fits streaming additions: each new cell increments the component count by one for itself, then unions decrement the count by one per successful merge. Using parent[u] = -1 as a “not land yet” marker avoids a separate boolean grid. The duplicate-position guard parent[u] != -1 ensures we don’t double-count.

Complexity#

  • Time: O(K * α(M * N)) for K positions.
  • Space: O(M * N).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.