Pattern this teaches:Graph BFS and DFS
Number of Islands
A medium Graph interview guide. Task statement, worked examples, intuition, and step-by-step solutions.
- Topic
- Graph
- Sheets
- 3
- Core for
- 12 roles
The problem
A grid shows land as '1' and water as '0'. Land cells that touch up, down, left or right belong to the same island; diagonal contact does not count. Everything outside the grid is water. Return how many separate islands there are.
Example 1
- Input
- grid = [["1","1","1"],["0","1","0"],["1","1","1"]]
- Output
- 1
- Why
- All 1s connect through the center to form a single island.
Example 2
- Input
- grid = [["1","1","0","0"],["1","1","0","0"],["0","0","1","1"],["0","0","1","1"]]
- Output
- 2
- Why
- Two separate 2x2 blocks of 1s form two distinct islands.
Constraints
- m == grid.length
- n == grid[i].length
- 1 <= m, n <= 300
- grid[i][j] is '0' or '1'
How to think about it
Updated 2026-09-29Every unvisited land cell is an undiscovered piece of territory. When a sweep finds one, you have discovered an entirely new island, so increment the counter and immediately flood the entire component into visited state before resuming the scan. The grid itself can serve as its own visited log by sinking land to water.
Approaches, worst first
Connected component with global visited set
time O(m * n) · space O(m * n)
Scan row by row. Whenever a '1' is not in a hash set of visited coordinates, fire a BFS or DFS traversal adding every reachable neighbor into the set. Correct, but allocating coordinates into a hash set adds heavy hashing overhead and pointer indirection.
In-place grid sinking DFS or BFSWrite this one
time O(m * n) · space O(m * n)
When encountering '1', trigger an in-place flood fill that mutates visited cells from '1' to '0'. This eliminates external tracking structures entirely, leaving only the recursion stack or queue bounded by grid size.
Where people lose marks · 3
- In deep or snake-shaped islands on a 300x300 grid, recursive DFS can reach recursion depths up to 90,000, which will exceed call stack limits in languages with standard stack sizes.
- Forgetting to mark a cell visited as soon as it is enqueued in BFS rather than when dequeued, causing identical adjacent cells to be added to the queue exponentially many times and producing memory exhaustion.
- Comparing grid values as numbers instead of characters; `grid[i][j] === 1` silently fails when inputs are strings '1'.
Full solution
In-place grid sinking BFS: flood each newly found island to water as it is counted, so no external visited set is needed and, unlike recursive DFS, the queue never risks blowing the call stack on a large grid.
Python
from collections import deque
def num_islands(grid: list[list[str]]) -> int:
rows, cols = len(grid), len(grid[0])
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != "1":
continue
count += 1
# BFS sinks the whole component to "0" so it is never counted again,
# and a queue avoids the recursion-depth blowup a DFS risks on a big grid.
queue = deque([(r, c)])
grid[r][c] = "0"
while queue:
cr, cc = queue.popleft()
for nr, nc in ((cr - 1, cc), (cr + 1, cc), (cr, cc - 1), (cr, cc + 1)):
if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == "1":
grid[nr][nc] = "0"
queue.append((nr, nc))
return count
JavaScript
function numIslands(grid) {
const rows = grid.length;
const cols = grid[0].length;
let count = 0;
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
if (grid[r][c] !== "1") continue;
count++;
const queue = [[r, c]];
grid[r][c] = "0";
while (queue.length) {
const [cr, cc] = queue.shift();
for (const [nr, nc] of [[cr - 1, cc], [cr + 1, cc], [cr, cc - 1], [cr, cc + 1]]) {
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] === "1") {
grid[nr][nc] = "0";
queue.push([nr, nc]);
}
}
}
}
}
return count;
}
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 .