Number of Islands solution explained
To count islands, scan the grid cell by cell; each time you reach land that has not been visited, add one to the count and flood-fill the whole island with a breadth-first or depth-first search so none of its cells are counted again. Every cell is visited a constant number of times, so the Number of Islands solution runs in O(rows × columns) time.
By Evin JohnPublished 9 min read
The problem, in plain terms
You are handed a rectangular map split into square cells. Each cell is either land, written as 1, or water, written as 0. Two land cells belong to the same island if you can walk from one to the other stepping only onto land and only straight up, down, left or right. Diagonal steps do not count, and everything outside the map is water. Return how many separate islands the map contains.
Map A (answer: 3) Map B (answer: 1)
1 1 0 0 1 1 1 1
1 0 0 0 1 0 1 0
0 0 1 0 0 1 1 1
0 0 0 0 0In map A, the two cells at the top left form one island, the right column forms a second, and the lone cell in the middle is a third. In map B every land cell connects through the center, so there is just one. If the two cells of an island touched only at a corner, they would be two islands, which is the first thing to confirm with the interviewer.
Other questions worth asking: How big can the grid be? May I modify the input, or should it stay intact? Is the grid always rectangular, and can it be empty? The size question matters more than it looks, because a recursive search on a large all-land grid can run out of stack.
How the problem is used in interviews
Number of Islands is a common way to check whether a candidate can model a grid as a graph without being told to. It tests the mechanics of a traversal: bounds checks, marking cells as visited at the right moment, and choosing between recursion and an explicit queue or stack. Because the code is short, interviewers usually spend the remaining time on variations.
- Count diagonal neighbors too. Use eight directions instead of four. Nothing else changes.
- Return the area of the largest island. Have each flood fill count its cells and keep the maximum.
- Count islands with distinct shapes. Record each island's cells relative to its first cell and put the normalized shapes in a set.
- Land appears one cell at a time and you report the count after each addition. Rerunning the search each time is slow; union-find merges neighbors in nearly constant time per addition.
- The grid is too large to hold in memory. Read it row by row and merge labels between the current row and the previous one with union-find.
- Islands touching the border do not count. Flood-fill from every border land cell first, then count what remains.
A slower starting idea
One brute force gives every land cell its own label, then repeatedly lets each cell take the smallest label among its land neighbors until a full pass changes nothing. The number of distinct labels left is the answer. It is correct, but a long winding island can need a pass per cell along its length, so the worst case approaches O((rows × columns)²). Mentioning it briefly is fine. The real insight is that a single search from one cell can label the entire island at once.
The optimal approach: flood fill from each new island
Scan the cells in row order. Water and already-visited land are skipped. When the scan reaches unvisited land, that cell must belong to an island no earlier search touched, so add one to the count. Then start a search from it: put it in a queue, mark it visited, and repeatedly take a cell out and add its unvisited land neighbors, marking each as you add it. When the queue empties, the whole island is marked and the scan continues.
Mark a cell when you add it to the queue, not when you take it out. Marking late lets the same cell enter the queue several times through different neighbors, which wastes time and on dense grids can blow up memory.
from collections import deque
def count_islands(grid):
if not grid or not grid[0]:
return 0
rows, cols = len(grid), len(grid[0])
seen = [[False] * cols for _ in range(rows)]
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1 or seen[r][c]:
continue
islands += 1
seen[r][c] = True
queue = deque([(r, c)])
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 and not seen[nr][nc]:
seen[nr][nc] = True
queue.append((nr, nc))
return islands#include <utility>
#include <vector>
int countIslands(std::vector<std::vector<int>> grid) {
const int rows = static_cast<int>(grid.size());
if (rows == 0) return 0;
const int cols = static_cast<int>(grid[0].size());
const int dr[4] = {1, -1, 0, 0};
const int dc[4] = {0, 0, 1, -1};
int islands = 0;
std::vector<std::pair<int, int>> todo;
for (int r = 0; r < rows; ++r) {
for (int c = 0; c < cols; ++c) {
if (grid[r][c] != 1) continue;
++islands;
grid[r][c] = 0; // sink it so it is never counted again
todo.push_back({r, c});
while (!todo.empty()) {
auto [cr, cc] = todo.back();
todo.pop_back();
for (int k = 0; k < 4; ++k) {
int nr = cr + dr[k], nc = cc + dc[k];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && grid[nr][nc] == 1) {
grid[nr][nc] = 0;
todo.push_back({nr, nc});
}
}
}
}
}
return islands;
}A recursive depth-first search is shorter and perfectly acceptable for small grids, but say out loud that on a large island it can recurse once per cell. Python's default recursion limit is around a thousand frames, so a thousand-by-thousand map of solid land would fail. The two versions above avoid that by managing their own queue or stack.
Union-find, for the follow-ups
def count_islands_union_find(grid):
rows = len(grid)
cols = len(grid[0]) if rows else 0
parent = {}
def root(x):
while parent[x] != x:
parent[x] = parent[parent[x]] # path halving
x = parent[x]
return x
count = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1:
continue
parent[(r, c)] = (r, c)
count += 1
for nr, nc in ((r - 1, c), (r, c - 1)):
if nr >= 0 and nc >= 0 and grid[nr][nc] == 1:
a, b = root((r, c)), root((nr, nc))
if a != b:
parent[a] = b
count -= 1
return countOnly the neighbors above and to the left are checked because cells below and to the right have not been processed yet; they will look back at this cell when their turn comes. The same structure answers the one-cell-at-a-time follow-up: add the new cell, union it with any land neighbors, and the running count is the answer after each step.
Complexity summary
| Approach | Time | Extra space |
|---|---|---|
| Label propagation until stable | Up to O((R·C)²) | O(R·C) |
| BFS from each new island | O(R·C) | O(R·C) for the visited grid, and the queue is usually far smaller |
| DFS with an explicit stack, sinking land | O(R·C) | O(R·C) worst case for the stack and the copied grid |
| Union-find with path halving | Close to O(R·C) in practice; O(R·C·α(R·C)) with union by size too | O(R·C) |
The α in the last row is the inverse Ackermann function, which stays below five for any grid you could store. The snippet above uses path halving alone, which keeps trees shallow in practice; adding union by size or rank is what earns that tight bound, and it is worth saying so if asked. If you are allowed to modify the input, sinking land in place removes the separate visited grid.
Edge cases to try
- An empty grid, or a grid with rows but no columns.
- All water, which returns 0, and all land, which returns 1.
- A single row or a single column.
- Land cells that touch only diagonally, which must count separately.
- A long snake-shaped island that winds across the whole map.
- A large solid block of land, to show the search does not recurse once per cell.
Pitfalls
- Checking a neighbor's value before checking that its row and column are inside the grid. In Python, a row index of -1 silently reads the last row.
- Marking cells visited only when they leave the queue.
- Modifying the caller's grid without asking, when it may be needed later.
- Using a recursive search on a large map without mentioning the stack limit.
- Counting land cells instead of islands, or adding one for every search step rather than once per new search.
How to narrate it
Fictional example
- Candidate
- I will treat each land cell as a node with edges to its four neighbors, so an island is a connected component and I need to count components.
- Candidate
- I scan every cell. Unvisited land means a component nobody has reached, so I add one and run a breadth-first search to mark all of it. I mark on enqueue so no cell enters the queue twice.
- Candidate
- Every cell is looked at a constant number of times, so it is linear in the number of cells. I am using a queue instead of recursion because a large solid island could exceed the recursion limit.
Keep practicing
The queue in this walkthrough is the same tool that drives Binary Tree Level Order Traversal, where it reads a tree one level at a time. For a design problem with a very different feel, try the LRU Cache. Every walkthrough in the set is on the coding problems hub.
A practice partner: Natively
Grid problems are easier to discuss when you can see the map. In practice, Natively can read a grid problem from a screenshot on Mac or Windows and suggest whether a breadth-first search, a depth-first search or union-find fits, along with the bounds checks to watch. It also transcribes your mock round so you can review the explanation afterward. Read about the AI interview assistant for more.
Questions people ask
How do you solve Number of Islands?
Scan every cell. When you find land that has not been visited, add one to the count and run a breadth-first or depth-first search from it, marking every connected land cell so it is not counted again.
What is the time complexity of Number of Islands?
O(rows × columns), because each cell is checked a constant number of times. Extra space is up to O(rows × columns) for the visited marks and the queue or stack.
Should I use BFS or DFS for Number of Islands?
Either gives the right count. Iterative BFS or DFS with an explicit stack is safer on large grids, because a recursive search can exceed the recursion limit on a big island.
When is union-find better here?
When land is added one cell at a time and you need the count after each addition, or when the grid is read row by row. Union-find merges neighbors in nearly constant time.
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.
