Number of Islands II
A hard Graph interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Graph
- Sheets
- 1
- Core for
- 12 roles
The problem
Given an m x n grid initially all water (0), a list of positions where land (1) is added one at a time, and the grid dimensions, return an array where each element is the number of islands after adding land at that position.
Example 1
- Input
- m = 3, n = 3, positions = [[0,0],[0,1],[1,2],[2,1]]
- Output
- [1,1,2,3]
- Why
- After each addition: 1 island, still 1, then 2 islands, then 3 islands.
Example 2
- Input
- m = 2, n = 2, positions = [[0,0],[0,1],[1,1],[1,0]]
- Output
- [1,1,1,1]
- Why
- All positions eventually form one connected island.
Constraints
- 1 <= m, n <= 200
- 1 <= positions.length <= 10^4
How to think about it
Updated 2026-09-29The grid is dynamically mutating as land cells are added one by one. Recalculating connected components from scratch after each insertion is far too slow. Instead, treat each newly added land cell as a brand new island (incrementing the island count by 1), then check its 4 cardinal neighbors: for each adjacent land cell in a distinct component, union them and decrement the count.
Approaches, worst first
Per-operation grid flood fill
time O(K * m * n) · space O(m * n)
After inserting each land cell, perform a full BFS or DFS sweep across the entire grid to count connected components from scratch. Recomputing components for every query wastes immense work instead of maintaining dynamic connectivity with disjoint sets.
Incremental DSU on flattened grid indicesWrite this one
time O(K * α(m * n)) · space O(m * n)
Flatten coordinates via `r * n + c`. Maintain a parent array initialized to -1. When land is added at `(r, c)`, if already land, append current count. Otherwise mark parent, increment count, and union with any existing adjacent land neighbors, decrementing count on successful unions.
Where people lose marks · 3
- Duplicate positions in the input: adding land to a cell that is ALREADY land must not increment island count or alter components.
- Flattening row and col: using `r * m + c` instead of `r * n + c` causes index overlapping when m != n.
- Accessing neighbors out of grid bounds (e.g. r - 1 < 0 or c + 1 >= n).
Full solution
C++
#include <bits/stdc++.h>
using namespace std;
struct DSU {
vector<int> parent;
DSU(int n) : parent(n) {
iota(parent.begin(), parent.end(), 0);
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
bool unite(int x, int y) {
int rx = find(x), ry = find(y);
if (rx == ry) return false;
parent[rx] = ry;
return true;
}
};
vector<int> numOfIslands(int rows, int cols, vector<vector<int>>& operators) {
vector<vector<int>> grid(rows, vector<int>(cols, 0));
DSU dsu(rows * cols);
int count = 0;
vector<int> res;
int dr[] = {-1, 1, 0, 0};
int dc[] = {0, 0, -1, 1};
for (const auto& op : operators) {
int r = op[0], c = op[1];
if (r >= 0 && r < rows && c >= 0 && c < cols) {
if (grid[r][c] == 1) {
res.push_back(count);
continue;
}
grid[r][c] = 1;
int idx = r * cols + c;
count++;
for (int k = 0; k < 4; k++) {
int nr = r + dr[k], nc = c + dc[k];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {
int nidx = nr * cols + nc;
if (dsu.unite(idx, nidx)) {
count--;
}
}
}
}
res.push_back(count);
}
return res;
}
Java
import java.util.*;
public class Main {
static class DSU {
int[] parent;
DSU(int n) {
parent = new int[n];
for (int i = 0; i < n; i++) parent[i] = i;
}
int find(int x) {
if (parent[x] != x) parent[x] = find(parent[x]);
return parent[x];
}
boolean unite(int x, int y) {
int rx = find(x), ry = find(y);
if (rx == ry) return false;
parent[rx] = ry;
return true;
}
}
static int[] numOfIslands(int rows, int cols, int[][] operators) {
int[][] grid = new int[rows][cols];
DSU dsu = new DSU(rows * cols);
int count = 0;
int[] res = new int[operators.length];
int[] dr = {-1, 1, 0, 0};
int[] dc = {0, 0, -1, 1};
for (int i = 0; i < operators.length; i++) {
int r = operators[i][0], c = operators[i][1];
if (r >= 0 && r < rows && c >= 0 && c < cols) {
if (grid[r][c] == 1) {
res[i] = count;
continue;
}
grid[r][c] = 1;
int idx = r * cols + c;
count++;
for (int k = 0; k < 4; k++) {
int nr = r + dr[k], nc = c + dc[k];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {
int nidx = nr * cols + nc;
if (dsu.unite(idx, nidx)) {
count--;
}
}
}
}
res[i] = count;
}
return res;
}
}
Python
def num_of_islands(rows, cols, operators):
parent = {}
def find(x):
if parent[x] != x:
parent[x] = find(parent[x])
return parent[x]
grid = [[0] * cols for _ in range(rows)]
count = 0
res = []
for r, c in operators:
if 0 <= r < rows and 0 <= c < cols:
if grid[r][c] == 1:
res.append(count)
continue
grid[r][c] = 1
idx = r * cols + c
parent[idx] = idx
count += 1
for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
nidx = nr * cols + nc
root1 = find(idx)
root2 = find(nidx)
if root1 != root2:
parent[root1] = root2
count -= 1
res.append(count)
return res
JavaScript
function numOfIslands(rows, cols, operators) {
const parent = new Map();
function find(x) {
if (parent.get(x) !== x) {
parent.set(x, find(parent.get(x)));
}
return parent.get(x);
}
const grid = Array.from({ length: rows }, () => Array(cols).fill(0));
let count = 0;
const res = [];
for (const [r, c] of operators) {
if (r >= 0 && r < rows && c >= 0 && c < cols) {
if (grid[r][c] === 1) {
res.push(count);
continue;
}
grid[r][c] = 1;
const idx = r * cols + c;
parent.set(idx, idx);
count++;
for (const [dr, dc] of [[-1, 0], [1, 0], [0, -1], [0, 1]]) {
const nr = r + dr;
const nc = c + dc;
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === 1) {
const nidx = nr * cols + nc;
const root1 = find(idx);
const root2 = find(nidx);
if (root1 !== root2) {
parent.set(root1, root2);
count--;
}
}
}
}
res.push(count);
}
return res;
}
The theory behind it
Graph — the ground this problem stands on. All Graph problems
What Graph is
A graph is a network of individual points, called vertices or nodes, connected by lines called edges. Think of a subway transit map, an electrical circuit, or a web of social friends. Unlike a tree, a graph has no designated top node and no parent-child hierarchy. Connections can run one-way or both ways, and paths can loop back on themselves to form closed cycles.
When to reach for it
Reach for graph algorithms when inputs describe relationships, networks, flights between cities, course prerequisites, or clone networks. Signals include finding the shortest route across unweighted connections, ordering tasks that depend on earlier tasks, counting isolated clusters, or checking whether a path contains an infinite loop. Whenever problems present pairs of related entities and ask for reachability, distances, or dependencies, graph representations apply.
How the pattern works
First convert edge lists into an adjacency list, mapping each node to an array of its neighbors. Choose your exploration strategy based on the goal: use a queue and breadth-first search to find the shortest path in unweighted networks, or use recursion and depth-first search to explore full paths and detect cycles. Because graphs can have loops, always track visited nodes in a set or boolean array. Add nodes to the visited set at the moment they enter the queue so they are never visited twice.
More Graph problems
Target Roles
Core requirement for 12 roles:
Track in your role's order
Pick your target role and all 370 problems resequence to what that interview actually asks.
Start freeProblem set and role mapping as of .