Number of Islands II solution explained
Number of Islands II is solved with union-find: each time a water cell becomes land, add it as a new island, then union it with every land neighbor and subtract one from the count for each union that actually merges two different sets. Repeated cells leave the count unchanged. With path compression plus union by size, the k additions cost close to O(k) in total, instead of recounting the whole grid after every step.
By Evin JohnPublished 8 min read
The problem, restated
You are given the size of a grid, rows by cols, where every cell starts as water. Then you get a list of cells, and one by one each cell turns into land. Two land cells belong to the same island if they share an edge, up, down, left or right; diagonals do not count. After each addition, record the current number of islands. Return the list of counts, one per addition.
| Step | Cell added | Islands after | What happened |
|---|---|---|---|
| 1 | (0, 0) | 1 | First land |
| 2 | (0, 2) | 2 | Not touching (0, 0) |
| 3 | (1, 1) | 3 | Touches neither, diagonals do not count |
| 4 | (0, 1) | 1 | Bridges all three islands into one |
| 5 | (2, 3) | 2 | A new island in the far corner |
| 6 | (1, 1) | 2 | Already land, nothing changes |
| 7 | (2, 2) | 2 | Joins the corner island only |
Step 4 is the interesting one: a single cell can merge up to four islands, so the count can drop by more than one in a step. Step 6 is the trap: the same cell may appear twice, and if you treat it as new land you will add an island that does not exist. Ask the interviewer whether repeats can happen, and handle them either way.
Why interviewers like it
Plenty of candidates know the original island count, a flood fill over a fixed grid. This version checks whether you can recognize when a one-time algorithm stops fitting. The grid changes over time and you need an answer after each change, which is the textbook setting for a disjoint set, also called union-find. It is also a test of careful bookkeeping: what exactly changes in the count when one cell flips?
Slow approach: recount after every step
Keep a set of land cells. After each addition, run a breadth-first search from every unvisited land cell and count how many searches you start. That is the classic island count, repeated k times.
from collections import deque
def island_counts_slow(rows, cols, cells):
land, result = set(), []
for cell in cells:
land.add(tuple(cell))
seen, islands = set(), 0
for start in land:
if start in seen:
continue
islands += 1
seen.add(start)
queue = deque([start])
while queue:
r, c = queue.popleft()
for nxt in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if nxt in land and nxt not in seen:
seen.add(nxt)
queue.append(nxt)
result.append(islands)
return resultIt is easy to get right, and it is a good baseline to compare against. But with ten thousand additions on a large grid it repeats almost the same work every time, since one new cell changes very little.
Main approach: union-find with a running count
Give every cell an id, row × cols + col. Keep a parent pointer for each land cell; following parents leads to a representative, or root, for the island. Keep a running island count. When a cell turns to land, first check whether it is already land. If so, record the current count and move on. Otherwise make it its own root and add one to the count. Then look at its four neighbors. For each neighbor that is inside the grid and is land, find both roots. If they differ, point one root at the other and subtract one. If they are the same, the two cells were already connected through some other path, and nothing changes.
That last case is why you must compare roots and not just count land neighbors. In step 4 of the example, (0, 1) has three land neighbors and three distinct roots, so the count goes 4, 3, 2, 1. In a different grid, two of those neighbors might already share an island, and only one union would succeed.
def island_counts(rows, cols, cells):
parent = {}
def root(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
result, islands = [], 0
for r, c in cells:
cell = r * cols + c
if cell not in parent:
parent[cell] = cell
islands += 1
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and nr * cols + nc in parent:
a, b = root(cell), root(nr * cols + nc)
if a != b:
parent[a] = b
islands -= 1
result.append(islands)
return resultfunction islandCounts(rows, cols, cells) {
const parent = new Int32Array(rows * cols).fill(-1);
const root = (x) => {
while (parent[x] !== x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
};
const moves = [[1, 0], [-1, 0], [0, 1], [0, -1]];
const result = [];
let islands = 0;
for (const [r, c] of cells) {
const id = r * cols + c;
if (parent[id] === -1) {
parent[id] = id;
islands += 1;
for (const [dr, dc] of moves) {
const nr = r + dr;
const nc = c + dc;
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
const nid = nr * cols + nc;
if (parent[nid] === -1) continue;
const a = root(id);
const b = root(nid);
if (a !== b) {
parent[a] = b;
islands -= 1;
}
}
}
result.push(islands);
}
return result;
}The two versions show a real design choice. The typed array allocates rows × cols slots up front, which is fast and fine for moderate grids. The dictionary only stores cells that became land, which matters when the grid is enormous and the list of additions is short. Mention whichever you pick and why.
Complexity
| Approach | Time | Memory | Comment |
|---|---|---|---|
| Flood fill after each step | O(k · m · n) | O(m · n) | Simple, repeats work |
| Union-find, path halving only | O(k log(m · n)) amortized | O(k) with a dictionary | What most candidates write |
| Union-find, halving plus union by size | O(k · α(m · n)), nearly linear | O(k) or O(m · n) | The textbook bound |
α is the inverse Ackermann function, which stays below 5 for any input you will ever see. Path compression alone already gives logarithmic amortized cost per operation, and adding union by size or rank brings it down to that near-constant bound. In an interview, path compression is usually enough; mention union by size as an upgrade.
Edge cases
- The same cell added twice: the count must not change the second time.
- Cells on the border: neighbors outside the grid must be skipped, not looked up.
- A 1 by n strip: additions can only merge left and right, which is a good quick test.
- An empty list of additions: return an empty list.
- A cell that touches the same island from two sides: only one of the two unions should succeed.
Mistakes to avoid
- Flattening (row, col) to row × cols + col without a bounds check. The cell to the right of the last column then aliases to the first column of the next row, and you merge islands that do not touch.
- Subtracting one for every land neighbor instead of every successful union.
- Forgetting that find must run on both cells, not on the neighbor alone.
- Allocating a full grid when the grid is huge but the additions are few.
- Recursing deeply in find without compression, which can hit recursion limits on long snakes of land.
Explaining it in the room
Fictional example
- Candidate
- Recounting after every addition repeats a full flood fill each time, so I would rather maintain the answer as the grid changes.
- Candidate
- A new land cell is a new island, so plus one. Then for each land neighbor I compare roots in a union-find; every time the roots differ I merge and subtract one.
- Candidate
- If the cell is already land I just repeat the last count. With path compression each step is close to constant time.
More union-find practice
Smallest String With Swaps uses the same structure on string positions instead of grid cells, and Minimum Time to Complete Trips is the binary search problem just before this one in the set. For a broader review of disjoint sets, heaps and graphs, see the data structure interview questions page.
Working on it with Natively
Natively can take a screenshot of a grid problem during practice and suggest a pattern and code, which works best as a check after you have sketched the union-find on your own. It also transcribes each mock session on your computer, so you can confirm you explained the repeat-cell case and the bounds check. Read about an AI interview assistant for Mac and Windows.
Questions people ask
How do you solve Number of Islands II?
Use union-find over cell ids. Each new land cell adds one island; then union it with each land neighbor and subtract one whenever the two cells had different roots. Record the count after every addition.
What happens if the same cell is added twice?
Nothing changes. Check whether the cell is already land before adding it, and if it is, record the current count again.
What is the time complexity of the union-find solution?
With path compression and union by size, k additions cost O(k · α(m · n)), which is nearly linear. Path compression alone gives O(log) amortized per operation, which is fine in an interview.
Why not just run a flood fill after each addition?
It is correct but repeats almost all the work every step, costing up to O(m · n) per addition. Union-find only touches the new cell and its four neighbors.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
