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, where m = len(grid) and n = len(grid[0])
  • Each element grid[r][c] is either '0' or '1'.

Step-by-step walkthrough

  1. Understand the grid and what makes an island

    We are given an m x n grid 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 (1 and 0). - 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 to 90,000 cells in a single grid.
  2. 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 island
    

    A purely local check counts 2 islands when there is really only 1. 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'.

  3. Key idea: Scan the grid and flood-fill each new island

    Keep a visited table of False values with the same m x n shape as grid so 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: - If grid[row][col] is '0', ignore it (water). - If grid[row][col] is '1' and visited[row][col] is True, ignore it (already counted as part of an earlier island). - If grid[row][col] is '1' and visited[row][col] is False, we have just stepped onto a brand-new island: 1. Increment island_count by 1. 2. Run a flood fill starting at (row, col) to visit every reachable land cell (up, down, left, right) and mark visited[r][c] = True on 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.

  4. 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, a 300 x 300 grid of all '1's is one giant island of 90,000 cells, and Python's default recursion limit is only 1,000 nested calls—so recursion crashes with RecursionError.

    Instead, we store pending (row, col) coordinates in our own Python list stack: - Mark visited before pushing onto stack, not after popping. Otherwise, a cell shared by multiple land neighbors can be pushed onto the stack multiple times before it gets popped. - Check 0 <= next_row < num_rows and 0 <= next_col < num_cols explicitly, because grid[-1] in Python wraps around to the bottom row instead of raising IndexError!

    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_islands simply runs the outer scan and triggers flood_fill_island on 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_count
    
  5. Trace Example 1 step by step

    Watch how the scan discovers and labels the four islands (A, B, C, D) in the 3 x 5 grid 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
    
    1. (0, 0) is '1' and unvisited -> island_count = 1. Flood fill marks (0, 0), (1, 0), and (1, 1) (Island A).
    2. (0, 2) is '1' and unvisited (it meets (1, 1) only diagonally) -> island_count = 2. Flood fill marks (0, 2) and (0, 3) (Island B), and (0, 3) is then skipped when the outer scan reaches it.
    3. (1, 0) and (1, 1) are already visited and skipped. (1, 4) is '1' and unvisited -> island_count = 3. Flood fill marks (1, 4) and (2, 4) (Island C).
    4. (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) (Island D), and (2, 4) is skipped as already visited. Final answer: 4.
  6. 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 the m * n cells once, and because every land cell is marked visited the moment it is pushed onto stack, each cell is popped at most once and checks its 4 neighbors once.
  • Space: O(m * n). The visited matrix stores m * n booleans, and in the worst case (an all-land grid) stack can hold O(m * n) coordinates simultaneously.

Edge cases

  • All water ([['0', '0'], ['0', '0']]): Flood fill is never called and the function returns 0.
  • Single cell ([['1']] or [['0']]): Returns 1 or 0 cleanly with all four neighbor checks out of bounds.
  • Diagonal-only contact ([['1', '0'], ['0', '1']]): Counted as 2 islands because diagonal moves are excluded from neighbor_offsets.
  • U-shaped or spiral islands: Arms that appear separate in top rows but join further down are traversed together and counted as 1 island.
  • 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 as 2 islands.
  • Maximum size (300 x 300 all '1's): 90,000 connected land cells finish smoothly without hitting RecursionError thanks to the explicit stack.

Common mistakes

  • Using recursive DFS in Python: Hits RecursionError whenever a single island exceeds ~1,000 cells (well below 300 * 300 = 90,000).
  • Comparing grid[r][c] == 1 instead of grid[r][c] == "1": Because cells are one-character strings, comparing against integer 1 always evaluates to False and returns 0.
  • Omitting next_row >= 0 or next_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 visited on pop instead of on push: If you wait until stack.pop() to set visited[r][c] = True, all four neighbors of an unpopped cell can push duplicates of (r, c) onto stack, inflating peak stack size up to 4x.
  • Assuming num_rows == num_cols: Always read len(grid) for rows and len(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 of stack.pop()), achieving the same O(m * n) time and O(m * n) worst-case space (actually O(min(m, n)) queue space on a rectangular grid!).
  • In-place sinking (mutating grid): Overwriting visited '1' cells with '0' eliminates the visited array (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 (find and union), merging each '1' with its right and bottom '1' neighbors in nearly O(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 allocating visited, and use a collections.deque for BFS rather than a DFS stack. On an m x n grid, the active frontier of a grid BFS holds at most O(min(m, n)) cells at one time, lowering auxiliary space from O(m * n) to O(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 increments island_count by 1 and checks its 4 orthogonal neighbors, calling union and decrementing island_count by 1 each 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) to neighbor_offsets, keeping the exact same O(m * n) runtime. Finding the largest landmass's size requires counting how many cells flood_fill_island pops for each island, returning that integer area, and tracking max_area = max(max_area, area) across the scan.

Follow-up questions

Similar questions

More Samsung interview questions

All 5 Samsung questions →