Number of Islands II
Pattern: Disjoint set union
Land is added one cell at a time; report the number of islands after each addition. A new land cell is a new island, then each neighbouring land cell in a different group merges into it, lowering the count. Union-find handles it in almost constant time per step.
The problem
An m × n grid starts as water. Each position in positions turns that cell into land. Return the number of islands
after each addition. A cell may be added twice; the second time changes nothing. LeetCode's version is premium.
Think first
- Why not count islands from scratch each time?
- What can one new land cell do to the count?
- How do you avoid counting a merge twice?
Hints
Brute force, and why it fails
Rerun Number of Islands after each addition: O(k × m × n).
The key insight
Each addition only changes the groups around one cell, which union-find updates almost instantly.
Dry run
| out | 1 1 |
|---|
3 × 3 grid. Add (0, 0): 1 island. Add (0, 1): it joins (0, 0): still 1.
The plan
for each position: if water: make it land, islands += 1
for each land neighbour: if roots differ: union; islands -= 1
record islands
Complexity
- Time
O(k α(m n))- Space
O(m × n)
One union-find step per neighbour.
Edge cases
- The same cell twice.
- A cell joining four islands at once.
- A 1 × 1 grid.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> numIslands2(int m, int n, int[][] positions) {
int[] parent = new int[m * n];
Arrays.fill(parent, -1); // -1: water
List<Integer> out = new ArrayList<>();
int islands = 0;
int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
for (int[] p : positions) {
int id = p[0] * n + p[1];
if (parent[id] == -1) { // the same cell may be added twice
parent[id] = id;
islands++; // a new island ...
for (int[] d : dirs) {
int r = p[0] + d[0], c = p[1] + d[1], nid = r * n + c;
if (r < 0 || c < 0 || r >= m || c >= n || parent[nid] == -1) continue;
int a = find(parent, id), b = find(parent, nid);
if (a != b) { parent[a] = b; islands--; } // ... that may join neighbouring ones
}
}
out.add(islands);
}
return out;
}
private int find(int[] parent, int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
}C++
class Solution {
public:
vector<int> numIslands2(int m, int n, vector<vector<int>>& positions) {
vector<int> parent(m * n, -1); // -1: water
vector<int> out;
int islands = 0;
int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
for (const vector<int>& p : positions) {
int id = p[0] * n + p[1];
if (parent[id] == -1) { // the same cell may be added twice
parent[id] = id;
islands++; // a new island ...
for (int k = 0; k < 4; k++) {
int r = p[0] + dr[k], c = p[1] + dc[k], nid = r * n + c;
if (r < 0 || c < 0 || r >= m || c >= n || parent[nid] == -1) continue;
int a = find(parent, id), b = find(parent, nid);
if (a != b) { parent[a] = b; islands--; } // ... that may join neighbouring ones
}
}
out.push_back(islands);
}
return out;
}
int find(vector<int>& parent, int x) {
while (parent[x] != x) x = parent[x] = parent[parent[x]];
return x;
}
};Python
class Solution:
def numIslands2(self, m: int, n: int, positions: list[list[int]]) -> list[int]:
parent = {} # land cells only
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
out, islands = [], 0
for r, c in positions:
if (r, c) not in parent: # the same cell may be added twice
parent[(r, c)] = (r, c)
islands += 1 # a new island ...
for nb in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if nb in parent:
a, b = find((r, c)), find(nb)
if a != b:
parent[a] = b # ... that may join neighbouring ones
islands -= 1
out.append(islands)
return outCommon mistakes
- Counting a repeated position again.
- Subtracting for neighbours already in the same group.