Count Islands in a Grid
Medium · Coding & Algorithms · Software Engineer · Onsite
Problem Statement
You are given a rectangular 2D matrix grid whose entries are single-character strings: "1" denotes dry land and "0" denotes open water. Everything outside the boundaries of the matrix is treated as water.
Two land cells belong to the same island whenever they share a horizontal or vertical edge (up, down, left, or right). Cells that meet only at a diagonal corner do not connect directly. An island is a maximal connected group of "1" cells.
Implement num_islands(grid) to return the total number of distinct islands in grid:
def num_islands(grid: List[List[str]]) -> int:
Use an iterative breadth-first search (BFS) traversal so deep or winding landmasses cannot exceed Python's call-stack limit, and handle empty-matrix corner cases ([] and [[]]) cleanly by returning 0.
Examples
Example 1
Input:
grid = [
["1", "0", "1", "1"],
["1", "0", "1", "0"],
["1", "1", "1", "0"]
]
Output: 1
Every "1" cell belongs to a single U-shaped landmass: the left column (0, 0) -> (1, 0) -> (2, 0) connects across the bottom row to (2, 2), rises up column 2 to (0, 2), and extends right to (0, 3).
Example 2
Input:
grid = [
["1", "1", "0", "0"],
["0", "1", "0", "1"],
["0", "0", "1", "0"],
["0", "0", "1", "1"]
]
Output: 3
There are three separate islands: {(0, 0), (0, 1), (1, 1)} in the upper-left, the isolated cell {(1, 3)} on the right edge, and {(2, 2), (3, 2), (3, 3)} near the bottom-right. Although (2, 2) touches both (1, 1) and (1, 3) diagonally, corner contact does not merge islands.
Constraints
0 <= len(grid) <= 3000 <= len(grid[r]) <= 300, and all rows ingridhave the same length- Each entry
grid[r][c]is either"0"or"1"
Step-by-step walkthrough
Understand the grid and island rules
We are given a 2D
gridof strings'1'(land) and'0'(water) and asked to count how many islands it contains, using breadth-first search (BFS) and handling every corner case cleanly.Before writing code, lock down the exact rules: - 4-directional connection only: Two
'1'cells belong to the same island if they share an edge up, down, left, or right. Touching only diagonally ([['1', '0'], ['0', '1']]) forms 2 separate islands. - Strings, not integers: Every cell holds'1'or'0', not1or0('1' == 1isFalsein Python!). - Out-of-bounds is water: Everything outside0 .. rows - 1and0 .. cols - 1is water (the grid does not wrap around at edges). - Empty inputs:[]and[[]]contain0islands. - Preserving the caller's input: Overwriting'1'with'0'works, but mutatesgrid; using a separateseenboolean matrix keeps the input untouched.Key idea: scan and flood-fill each island once
Think of land cells as nodes connected to their up/down/left/right land neighbors. Each island is one connected component (a maximal group of linked land cells).
Why can't we just scan top-to-bottom, left-to-right and count every
'1'that has water above it and to its left? Because an island can curve like aU:1 0 1 <-- top-left '1' and top-right '1' both look like "new" starts... 1 0 1 1 1 1 <-- ...until the bottom row connects them into ONE island!Instead, we combine a grid scan with a flood fill (spreading out from one starting cell across all connected land cells in all four directions): 1. Scan every
(r, c)in the grid. 2. Skip water ('0') and already-visited land (seen[r][c] == True). 3. Whenever we hit an unvisited'1', incrementislands += 1and immediately flood-fill its entire connected island (moving down, up, right, and left) so none of its remaining cells will ever start a second count.Why BFS beats recursive DFS on large grids
There are two standard ways to run a flood fill: - Recursive depth-first search (DFS) calls a function on each neighbor. On a
200 x 200all-land grid (40,000connected cells), recursion can go40,000frames deep — crashing past Python's default recursion limit of1,000(RecursionError). - Breadth-first search (BFS) uses acollections.deque(a double-ended queue withO(1)appendat the back andO(1)popleftfrom the front) to explore neighbors wave by wave in plain loops, so recursion depth is zero.One BFS rule is critical: mark
seen[next_r][next_c] = Trueat the moment youappenda cell to the queue, NOT when youpopleftit later! Watch what happens on a tiny2 x 2all-land grid if you wait untilpopleftto markseen:1 1 1 1 Pop (0, 0) -> enqueues (1, 0) and (0, 1). Queue is [(1, 0), (0, 1)], and (1, 1) is STILL unmarked: - Pop (1, 0) -> sees (1, 1) unmarked -> enqueues (1, 1) - Pop (0, 1) -> STILL sees (1, 1) unmarked -> enqueues (1, 1) AGAIN!Across larger grids, duplicate pushes snowball exponentially unless prevented. Marking
seenbeforequeue.append(...)guarantees every land cell enters the queue at most once.Implement the BFS helper mark_island
Notice how we check
0 <= next_r < rows and 0 <= next_c < colsbefore indexinggrid[next_r][next_c]. In Python,grid[-1]is valid syntax for the last row — without0 <= next_r, stepping up from row0would silently wrap around to rowrows - 1!from collections import deque from typing import List # Four orthogonal step offsets (row_delta, col_delta): down, up, right, left. # Diagonal neighbors are omitted because corner-touching land does not connect. DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def mark_island( grid: List[List[str]], seen: List[List[bool]], start_r: int, start_c: int ) -> None: """Breadth-first search from (start_r, start_c) marking every cell in this island.""" rows = len(grid) cols = len(grid[0]) # queue: FIFO deque of (row, col) land cells whose 4 neighbors still need checking. seen[start_r][start_c] = True queue = deque([(start_r, start_c)]) while queue: r, c = queue.popleft() for dr, dc in DIRECTIONS: next_r = r + dr next_c = c + dc # Check bounds BEFORE indexing grid: in Python, grid[-1] wraps to the last row! in_bounds = 0 <= next_r < rows and 0 <= next_c < cols if not in_bounds: continue if grid[next_r][next_c] == "1" and not seen[next_r][next_c]: # Mark as seen BEFORE enqueueing so two neighbors cannot push duplicate # copies of (next_r, next_c), which would otherwise blow up the queue. seen[next_r][next_c] = True queue.append((next_r, next_c))Implement the outer scan num_islands
Checking
if not grid or not grid[0]: return 0up front handles both[]and[[]]:from typing import List def num_islands(grid: List[List[str]]) -> int: # Handle empty corner cases: [] (zero rows) and [[]] (zero columns). if not grid or not grid[0]: return 0 rows = len(grid) cols = len(grid[0]) # seen: rows x cols boolean matrix tracking visited land without mutating `grid`. # Mini-shape for 2x2: [[True, False], [False, False]] seen = [[False] * cols for _ in range(rows)] islands = 0 # Scan every cell; each unvisited '1' discovers a brand-new island and flood-fills it. for r in range(rows): for c in range(cols): if grid[r][c] == "1" and not seen[r][c]: islands += 1 mark_island(grid, seen, r, c) return islandsWalk through Example 2
Grid: col: 0 1 2 3 row 0: 1 1 0 0 row 1: 0 1 0 1 row 2: 0 0 1 0 row 3: 0 0 1 1 1. Scan hits (0, 0) == '1' (unseen) -> islands = 1 BFS queue trace: start [(0,0)] -> pop (0,0), mark & push (0,1) pop (0,1) -> mark & push (1,1) pop (1,1) -> orthogonal neighbors are seen or '0' ((2,2) is diagonal, so ignored!) Island #1 marks {(0,0), (0,1), (1,1)}. 2. Scan skips seen cells and '0's until (1, 3) == '1' (unseen) -> islands = 2 BFS marks {(1,3)}; all 4 orthogonal neighbors are '0' or out of bounds. 3. Scan continues to (2, 2) == '1' (unseen) -> islands = 3 BFS marks {(2,2), (3,2), (3,3)}. Later scan positions (3, 2) and (3, 3) are already seen. Final answer: 3Full solution
from collections import deque from typing import Any, Dict, List, Optional, Set, Tuple # Four orthogonal step offsets (row_delta, col_delta): down, up, right, left. # Diagonal neighbors are omitted because corner-touching land does not connect. DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def mark_island( grid: List[List[str]], seen: List[List[bool]], start_r: int, start_c: int ) -> None: """Breadth-first search from (start_r, start_c) marking every cell in this island.""" rows = len(grid) cols = len(grid[0]) # queue: FIFO deque of (row, col) land cells whose 4 neighbors still need checking. seen[start_r][start_c] = True queue = deque([(start_r, start_c)]) while queue: r, c = queue.popleft() for dr, dc in DIRECTIONS: next_r = r + dr next_c = c + dc # Check bounds BEFORE indexing grid: in Python, grid[-1] wraps to the last row! in_bounds = 0 <= next_r < rows and 0 <= next_c < cols if not in_bounds: continue if grid[next_r][next_c] == "1" and not seen[next_r][next_c]: # Mark as seen BEFORE enqueueing so two neighbors cannot push duplicate # copies of (next_r, next_c), which would otherwise blow up the queue. seen[next_r][next_c] = True queue.append((next_r, next_c)) def num_islands(grid: List[List[str]]) -> int: # Handle empty corner cases: [] (zero rows) and [[]] (zero columns). if not grid or not grid[0]: return 0 rows = len(grid) cols = len(grid[0]) # seen: rows x cols boolean matrix tracking visited land without mutating `grid`. # Mini-shape for 2x2: [[True, False], [False, False]] seen = [[False] * cols for _ in range(rows)] islands = 0 # Scan every cell; each unvisited '1' discovers a brand-new island and flood-fills it. for r in range(rows): for c in range(cols): if grid[r][c] == "1" and not seen[r][c]: islands += 1 mark_island(grid, seen, r, c) return islands✅ Submit now — all tests should pass.
Intuition & how it works
Picture a map of '1' (land) tiles and '0' (water) tiles: as you scan across the map tile by tile, every time you land on an unpainted '1' tile, you add 1 to your island count and pour paint that spreads up, down, left, and right across every connected '1' tile until water stops it. Each island is a connected component (a maximal group of land tiles linked by valid steps), spreading paint across it is called a flood fill, and we run that spread using breadth-first search (BFS) — exploring connected tiles wave by wave with a first-in, first-out queue (collections.deque, a double-ended queue with O(1) appends at the back and pops from the front).
Simply counting '1' tiles that have '0' above and to their left fails whenever a U-shaped island has two separate northern tips that merge lower down. Using recursive depth-first search (DFS) — diving down one path via nested function calls before backtracking — visits the right cells on small grids, but on a 200 x 200 all-land grid (40,000 connected cells) it blows past Python's ~1,000-call stack limit with RecursionError. Iterative BFS uses zero recursion and visits every cell cleanly.
Walk through a tiny 2 x 3 example [['1', '1', '0'], ['1', '0', '1']]:
1. (0, 0) is an unseen '1': islands becomes 1, and BFS marks (0, 0) and enqueues [(0, 0)].
2. Popping (0, 0) marks and enqueues (1, 0) and (0, 1); popping (1, 0) and (0, 1) finds no further unseen '1' neighbors ((1, 2) is separated by '0').
3. The outer scan skips (0, 1) (seen), (0, 2) ('0'), (1, 0) (seen), and (1, 1) ('0'), then hits (1, 2) (unseen '1'), setting islands = 2 and returning 2.
Complexity
Let m be the number of rows and n be the number of columns.
- Time —
O(m * n): The outer loops inspect each of them * ncells once, and because we markseenbefore enqueueing, each land cell enters and leaves thedequeat most once and checks at most 4 neighbors (O(1)work per cell). - Space —
O(m * n): Theseenboolean matrix storesm * nentries, and the BFS queue holds only the active frontier of one island at a time (at mostO(min(m, n))on a single rectangular flood wave, and never more thanm * ncells in any shape).
Edge cases
- Empty grids (
[]and[[]]):if not grid or not grid[0]: return 0returns0before indexinggrid[0][0]. - All water or all land: All
'0's never triggersmark_island(0islands); all'1's triggersmark_islandonce at(0, 0)and marks the entirem x ngrid (1island, even at200 x 200). - Single-cell grids:
[['1']]returns1;[['0']]returns0. - Diagonal-only neighbors (
[['1', '0'], ['0', '1']]): Returns2; a5 x 5checkerboard with'1'on the corners has13islands (ceil(m * n / 2)is the theoretical maximum). - Ring island enclosing an inner lake island: Water inside a ring does not split the ring, and a
'1'inside that lake is counted separately (2islands total). - Winding
U- or spiral-shaped islands: Trying all 4 directions ((-1, 0)up and(0, -1)left included, not just right and down) ensures backward-curving arms are reached. - Opposite-edge cells (
[['1', '0', '0', '1']]): Explicit0 <= next_r < rowsand0 <= next_c < colsguards prevent wrapping across borders.
Common mistakes
- Comparing with integer
1instead of string'1':grid[r][c] == 1is alwaysFalsewhen cells are strings, silently returning0on every input. - Indexing
grid[next_r][next_c]before checkingnext_r >= 0andnext_c >= 0: In Python,grid[-1]reads the last row instead of raisingIndexError, falsely connecting the top edge to the bottom edge and the left edge to the right edge! - Marking
seenonpopleft()instead ofappend(): Waiting until removal lets multiple neighbors push duplicate copies of the same cell into the queue — without a secondseencheck on pop, duplicates cascade exponentially (C(r + c, r)copies at(r, c)on an all-land grid!). - Recursive DFS on large grids: Hits
RecursionErrorwhen an island has more than ~1,000 cells. - Mutating
gridin place (grid[r][c] = '0') unannounced: Saves theseenarray (O(min(m, n))BFS queue space), which is great if the caller allows destroyinggrid— always ask in an interview before mutating inputs.
Alternative approaches
- Iterative DFS with a Python list stack: Replace
dequeandpopleft()with a plainlistandpop(). It visits the exact same connected component inO(m * n)time without recursion, though peak stack size can reachO(m * n)even on an all-'1'rectangle (whereas BFS's diagonal wave frontier staysO(min(m, n))). - In-place sinking (
grid[r][c] = '0'): Overwriting visited'1's with'0'eliminates theO(m * n)seenmatrix, reducing extra memory toO(min(m, n))for the BFS frontier queue when mutatinggridis permitted. - Union-Find (Disjoint-Set Union): A union-find data structure tracks a collection of non-overlapping sets supporting
find(x)(which group doesxbelong to?) andunion(x, y)(merge two groups). Initializecountto the number of'1'cells, merge each'1'with its right and down'1'neighbors, and decrementcounton each successful merge — near-O(m * n)time and ideal when land arrives dynamically.
Follow-up questions
- If the map starts completely submerged and land coordinates arrive one by one, how can you report the island count after each addition? Re-running BFS from scratch on every addition would cost
O(k * m * n)acrosskadditions. Instead, use union-find with path compression (making nodes along afindchain point higher up toward their set's root so future lookups stay nearly flat): each new land cell incrementscountby1and checks its 4 neighbors, merging any distinct adjacent island sets and decrementingcountby1per merge in nearlyO(1)amortized time per addition.
def num_islands_online(positions):
parent = {}
def find(cell):
while parent[cell] != cell:
parent[cell] = parent[parent[cell]] # path halving
cell = parent[cell]
return cell
count = 0
history = []
for r, c in positions:
if (r, c) not in parent:
parent[(r, c)] = (r, c)
count += 1
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nb = (r + dr, c + dc)
if nb in parent:
root_a, root_b = find((r, c)), find(nb)
if root_a != root_b:
parent[root_a] = root_b
count -= 1
history.append(count)
return history
- What changes if diagonal neighbors also connect land cells (8-directional adjacency)? Simply add the four diagonal offsets
((1, 1), (1, -1), (-1, 1), (-1, -1))toDIRECTIONS; the BFS queue, bounds check,seenmarking, andO(m * n)time and space bounds stay identical (with 8 neighbor checks per cell instead of 4). - How would you count islands when the matrix has millions of rows streamed from disk one row at a time? You only ever need connectivity along the boundary of the previous row (
O(n)memory forncolumns). Assign component IDs to contiguous'1'runs in the incoming row (+1island per run), use union-find over the active row labels whenever a'1'touches a'1'directly above it in the previous row (-1island whenever two distinct component IDs merge), and compact/relabel only the surviving IDs present in the current row before reading the next row.
Follow-up questions
- If the map starts completely submerged and land coordinates arrive one by one, how can you report the island count after each addition?
- What changes if diagonal neighbors also connect land cells (8-directional adjacency)?
- How would you count islands when the matrix has millions of rows streamed from disk one row at a time?
Similar questions
- Sum Forward-Order Digit Lists
- Equalize Letter Counts by One Deletion
- Minimum Conference Rooms and Postfix Evaluator
- Directed Friend Requests Under Age Bounds
- Island Area Frequency Queries
- Dynamic Multiset Top-K Frequency Tracker
More Bloomberg interview questions
- Check Balanced Delimiter Nesting Medium
- Column-Order Binary Tree Traversal Medium
- Minimum Substitutions to Form an Anagram Medium Pro
- Enumerate Binary Strings From Wildcard Pattern Medium Pro
- Complete Concrete Subclasses in an Abstract Command Hierarchy Medium Pro
- Parse Clickstream URLs and Tracking Parameters in PostgreSQL Medium Pro
- Software Project Reflection and Technical Leadership Prompts Medium Pro
- Directed Friend Requests Under Age Bounds Medium Pro
- Leading Full-Cycle Client Software Delivery Hard Pro
- Low-Latency Streaming VWAP Market Data Engine Medium Pro