Count Orthogonal Land Regions
Easy · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
You are given an m x n 2D array grid whose entries are single-character strings: '1' denotes solid ground and '0' denotes open water. Everything outside the outer boundary of grid is also treated as water.
Two ground cells belong to the same island (land region) if one can be reached from the other by stepping repeatedly between orthogonally neighboring '1' cells—moving up, down, left, or right. Cells that touch only at a diagonal corner do not connect directly.
Implement count_islands(grid) to return the total number of separate islands present in grid.
def count_islands(grid: List[List[str]]) -> int:
Examples
Example 1
Input:
grid = [
["1", "0", "1", "1", "0"],
["1", "1", "0", "0", "1"],
["0", "0", "1", "0", "1"]
]
Output: 4
Walk-through:
- {(0, 0), (1, 0), (1, 1)} forms one L-shaped region of 3 cells.
- {(0, 2), (0, 3)} forms a second horizontal region of 2 cells (it touches (1, 1) and (1, 4) only diagonally).
- {(1, 4), (2, 4)} forms a third vertical region of 2 cells.
- {(2, 2)} forms a fourth isolated single-cell region.
Example 2
Input:
grid = [
["1", "1", "1", "0"],
["0", "0", "1", "0"],
["1", "0", "1", "1"]
]
Output: 2
Walk-through:
- Six cells—(0, 0), (0, 1), (0, 2), (1, 2), (2, 2), and (2, 3)—link orthogonally into one continuous region.
- Cell (2, 0) in the bottom-left corner is separated by '0' cells, giving a second region.
Constraints
1 <= m, n <= 300, wherem = len(grid)andn = len(grid[0])- Each element
grid[r][c]is either'0'or'1'.
Step-by-step walkthrough
Understand the grid and what makes an island
We are given an
m x ngrid of single-character strings:'1'represents land and'0'represents water. Two land cells belong to the same island if you can walk between them on land moving only up, down, left, or right (never diagonally).Pay attention to three key rules: - Grid entries are strings (
'1'and'0'), not integers (1and0). - Diagonal corners do not connect two land cells:1 0 0 1 -> 2 separate islands (only corners touch)- Dimensions reach
300 x 300, meaning up to90,000cells in a single grid.
- Dimensions reach
Why checking only top and left neighbors fails
When scanning row by row from top-left to bottom-right, it is tempting to count every
'1'whose top neighbor and left neighbor are both'0'(or out of bounds), assuming each such cell is the "top-left corner" of a distinct island.Look at what happens on a U-shaped island:
col: 0 1 2 r=0: 1 0 1 <- (0,0) has no land above/left (+1), AND (0,2) has no land above/left (+1)! r=1: 1 0 1 r=2: 1 1 1 <- bottom bridge joins both arms into 1 single islandA purely local check counts
2islands when there is really only1. Because two separate-looking branches can connect many rows later, we must explore the entire connected piece of land whenever we discover a new'1'.Key idea: Scan the grid and flood-fill each new island
Keep a
visitedtable ofFalsevalues with the samem x nshape asgridso we can remember which land cells have already been claimed without mutating the caller's input grid.Now scan every cell
(row, col)in row-by-row order: - Ifgrid[row][col]is'0', ignore it (water). - Ifgrid[row][col]is'1'andvisited[row][col]isTrue, ignore it (already counted as part of an earlier island). - Ifgrid[row][col]is'1'andvisited[row][col]isFalse, we have just stepped onto a brand-new island: 1. Incrementisland_countby1. 2. Run a flood fill starting at(row, col)to visit every reachable land cell (up, down, left, right) and markvisited[r][c] = Trueon all of them.Because the flood fill marks every cell of that island right away, the outer scan will skip all remaining cells of that island when it reaches them later.
Explore an island safely with an explicit stack
The shortest way to write flood fill is recursion, where visiting
(r, c)calls the function on its neighbors. However, a300 x 300grid of all'1's is one giant island of90,000cells, and Python's default recursion limit is only1,000nested calls—so recursion crashes withRecursionError.Instead, we store pending
(row, col)coordinates in our own Python liststack: - Markvisitedbefore pushing ontostack, not after popping. Otherwise, a cell shared by multiple land neighbors can be pushed onto the stack multiple times before it gets popped. - Check0 <= next_row < num_rowsand0 <= next_col < num_colsexplicitly, becausegrid[-1]in Python wraps around to the bottom row instead of raisingIndexError!def flood_fill_island( grid: List[List[str]], visited: List[List[bool]], start_row: int, start_col: int, ) -> None: """Mark every land cell reachable from (start_row, start_col) as visited.""" num_rows = len(grid) num_cols = len(grid[0]) # Four orthogonal neighbor offsets: down, up, right, left (diagonals do not connect). neighbor_offsets = ((1, 0), (-1, 0), (0, 1), (0, -1)) # stack: list of (row, col) land coordinates waiting to have their 4 neighbors checked. # Using an explicit stack avoids Python's ~1000-call recursion limit on 300x300 grids. visited[start_row][start_col] = True stack = [(start_row, start_col)] while stack: row, col = stack.pop() for row_delta, col_delta in neighbor_offsets: next_row = row + row_delta next_col = col + col_delta # Check 0 <= index < limit explicitly because negative indices in Python # silently wrap around to the opposite edge of the grid. in_bounds = 0 <= next_row < num_rows and 0 <= next_col < num_cols if not in_bounds: continue # Compare with string "1" (not integer 1), and mark visited BEFORE pushing # so multiple neighbors never push the same cell onto the stack twice. if grid[next_row][next_col] == "1" and not visited[next_row][next_col]: visited[next_row][next_col] = True stack.append((next_row, next_col))Then
count_islandssimply runs the outer scan and triggersflood_fill_islandon each unclaimed'1':def count_islands(grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 num_rows = len(grid) num_cols = len(grid[0]) # visited[r][c]: True once land cell (r, c) has been claimed by an explored island visited = [[False] * num_cols for _ in range(num_rows)] island_count = 0 # Scan every cell; each unvisited '1' is the first cell we see of a brand-new island. for row in range(num_rows): for col in range(num_cols): if grid[row][col] == "1" and not visited[row][col]: island_count += 1 flood_fill_island(grid, visited, row, col) return island_countTrace Example 1 step by step
Watch how the scan discovers and labels the four islands (
A,B,C,D) in the3 x 5grid from Example 1:Input grid: Claimed islands during scan: 0 1 2 3 4 0 1 2 3 4 0 1 0 1 1 0 0 A . B B . 1 1 1 0 0 1 1 A A . . C 2 0 0 1 0 1 2 . . D . C(0, 0)is'1'and unvisited ->island_count = 1. Flood fill marks(0, 0),(1, 0), and(1, 1)(IslandA).(0, 2)is'1'and unvisited (it meets(1, 1)only diagonally) ->island_count = 2. Flood fill marks(0, 2)and(0, 3)(IslandB), and(0, 3)is then skipped when the outer scan reaches it.(1, 0)and(1, 1)are alreadyvisitedand skipped.(1, 4)is'1'and unvisited ->island_count = 3. Flood fill marks(1, 4)and(2, 4)(IslandC).(2, 2)is'1'and unvisited ->island_count = 4. Its orthogonal neighbors are'0'or out of bounds, so flood fill marks only(2, 2)(IslandD), and(2, 4)is skipped as alreadyvisited. Final answer:4.
Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def flood_fill_island( grid: List[List[str]], visited: List[List[bool]], start_row: int, start_col: int, ) -> None: """Mark every land cell reachable from (start_row, start_col) as visited.""" num_rows = len(grid) num_cols = len(grid[0]) # Four orthogonal neighbor offsets: down, up, right, left (diagonals do not connect). neighbor_offsets = ((1, 0), (-1, 0), (0, 1), (0, -1)) # stack: list of (row, col) land coordinates waiting to have their 4 neighbors checked. # Using an explicit stack avoids Python's ~1000-call recursion limit on 300x300 grids. visited[start_row][start_col] = True stack = [(start_row, start_col)] while stack: row, col = stack.pop() for row_delta, col_delta in neighbor_offsets: next_row = row + row_delta next_col = col + col_delta # Check 0 <= index < limit explicitly because negative indices in Python # silently wrap around to the opposite edge of the grid. in_bounds = 0 <= next_row < num_rows and 0 <= next_col < num_cols if not in_bounds: continue # Compare with string "1" (not integer 1), and mark visited BEFORE pushing # so multiple neighbors never push the same cell onto the stack twice. if grid[next_row][next_col] == "1" and not visited[next_row][next_col]: visited[next_row][next_col] = True stack.append((next_row, next_col)) def count_islands(grid: List[List[str]]) -> int: if not grid or not grid[0]: return 0 num_rows = len(grid) num_cols = len(grid[0]) # visited[r][c]: True once land cell (r, c) has been claimed by an explored island visited = [[False] * num_cols for _ in range(num_rows)] island_count = 0 # Scan every cell; each unvisited '1' is the first cell we see of a brand-new island. for row in range(num_rows): for col in range(num_cols): if grid[row][col] == "1" and not visited[row][col]: island_count += 1 flood_fill_island(grid, visited, row, col) return island_count✅ Submit now — all tests should pass.
Intuition & how it works
Think of the paint-bucket tool in a drawing program: clicking one white pixel pours color across every touching white pixel until water borders stop the spread, while leaving disconnected shapes untouched. In graph terminology, each island is a connected component (a maximal group of nodes where every pair is linked by a path), and that paint-bucket operation is a flood fill (exploring outward from a starting cell through valid neighbors to mark an entire connected region). We scan the grid cell by cell; every time we land on an unpainted '1', we add 1 to our island count and run an iterative depth-first search (DFS) (exploring paths using a last-in, first-out stack of coordinates) to mark every cell of that island so we never count it a second time.
Why naive approaches fail:
Trying to avoid graph traversal by counting cells with water above and to their left miscounts U-shaped or winding islands whose two upper branches merge several rows lower. Conversely, writing flood fill with plain Python recursion relies on the call stack (the hidden memory frame stack tracking active function calls), which overflows Python's 1,000-call limit and crashes on a 300 x 300 all-land grid (90,000 cells).
Walkthrough on Example 2 ([['1', '1', '1', '0'], ['0', '0', '1', '0'], ['1', '0', '1', '1']]):
1. (0, 0) is '1' and unvisited: island_count becomes 1, and the stack flood-fill walks across (0, 0) -> (0, 1) -> (0, 2) -> (1, 2) -> (2, 2) -> (2, 3), marking all six cells visited.
2. As the outer scan continues across rows 0, 1, and 2, those five remaining cells are already marked visited and '0' cells are skipped.
3. (2, 0) is '1' and unvisited: island_count becomes 2, its neighbors (1, 0) and (2, 1) are '0', and the scan finishes by returning 2.
Complexity
Let m be the number of rows and n be the number of columns.
- Time:
O(m * n). The outer nested loop inspects each of them * ncells once, and because every land cell is markedvisitedthe moment it is pushed ontostack, each cell is popped at most once and checks its4neighbors once. - Space:
O(m * n). Thevisitedmatrix storesm * nbooleans, and in the worst case (an all-land grid)stackcan holdO(m * n)coordinates simultaneously.
Edge cases
- All water (
[['0', '0'], ['0', '0']]): Flood fill is never called and the function returns0. - Single cell (
[['1']]or[['0']]): Returns1or0cleanly with all four neighbor checks out of bounds. - Diagonal-only contact (
[['1', '0'], ['0', '1']]): Counted as2islands because diagonal moves are excluded fromneighbor_offsets. - U-shaped or spiral islands: Arms that appear separate in top rows but join further down are traversed together and counted as
1island. - Atoll / island inside a lake: A ring of
'1's surrounding water that encloses an inner'1'cannot cross the water gap, so it is properly counted as2islands. - Maximum size (
300 x 300all'1's):90,000connected land cells finish smoothly without hittingRecursionErrorthanks to the explicitstack.
Common mistakes
- Using recursive DFS in Python: Hits
RecursionErrorwhenever a single island exceeds ~1,000cells (well below300 * 300 = 90,000). - Comparing
grid[r][c] == 1instead ofgrid[r][c] == "1": Because cells are one-character strings, comparing against integer1always evaluates toFalseand returns0. - Omitting
next_row >= 0ornext_col >= 0: In Python,grid[-1][col]is valid syntax that reads the bottom row, accidentally connecting the top edge of the map to the bottom edge! - Marking
visitedon pop instead of on push: If you wait untilstack.pop()to setvisited[r][c] = True, all four neighbors of an unpopped cell can push duplicates of(r, c)ontostack, inflating peak stack size up to4x. - Assuming
num_rows == num_cols: Always readlen(grid)for rows andlen(grid[0])for columns so rectangular grids do not go out of bounds or miss columns.
Alternative approaches
- Breadth-first search (BFS) with
collections.deque: Breadth-first search (BFS) explores cells ripple-by-ripple in first-in, first-out order (queue.popleft()instead ofstack.pop()), achieving the sameO(m * n)time andO(m * n)worst-case space (actuallyO(min(m, n))queue space on a rectangular grid!). - In-place sinking (mutating
grid): Overwriting visited'1'cells with'0'eliminates thevisitedarray (O(1)extra space beyond the stack/queue), though in production and interviews you should ask before mutating the caller's input grid. - Union-Find (Disjoint-Set Union): A union-find data structure tracks disjoint groups using parent pointers (
findandunion), merging each'1'with its right and bottom'1'neighbors in nearlyO(m * n)time; it is slightly more code for a static grid, but shines when land cells are added dynamically.
Follow-up questions
- How can you lower the auxiliary space usage if mutating the input grid in place is permitted? Replace each visited
'1'directly with'0'("sinking" the island) instead of allocatingvisited, and use acollections.dequefor BFS rather than a DFS stack. On anm x ngrid, the active frontier of a grid BFS holds at mostO(min(m, n))cells at one time, lowering auxiliary space fromO(m * n)toO(min(m, n)). - Suppose the map starts completely submerged and cells turn into land one at a time; how would you report the island count after every update efficiently? Re-running flood fill from scratch on every query would take
O(m * n)per addition, which is too slow for thousands of updates. Instead, use a union-find structure: each newly added land cell incrementsisland_countby1and checks its4orthogonal neighbors, callingunionand decrementingisland_countby1each time a neighbor belongs to a different existing island—running in amortized near-O(1)time per addition. - How would the implementation change if diagonal contact also linked cells, or if you needed the size of the largest landmass instead? Allowing diagonal connections requires only adding the four corner offsets
(1, 1),(1, -1),(-1, 1), and(-1, -1)toneighbor_offsets, keeping the exact sameO(m * n)runtime. Finding the largest landmass's size requires counting how many cellsflood_fill_islandpops for each island, returning that integerarea, and trackingmax_area = max(max_area, area)across the scan.
Follow-up questions
- How can you lower the auxiliary space usage if mutating the input grid in place is permitted?
- Suppose the map starts completely submerged and cells turn into land one at a time; how would you report the island count after every update efficiently?
- How would the implementation change if diagonal contact also linked cells, or if you needed the size of the largest landmass instead?
Similar questions
- Largest Sum Without Adjacent Picks
- In-Place Alphanumeric Palindrome Check
- On-Site Office Laptop Estimation
- Sizing a Retail Customer Parking Lot
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
More Samsung interview questions
- In-Place Alphanumeric Palindrome Check Medium
- On-Site Office Laptop Estimation Medium
- Largest Sum Without Adjacent Picks Medium Pro
- Sizing a Retail Customer Parking Lot Medium Pro