Skip to content
mlmentorship

Count new component seeds and mark each whole region

Erase land on discovery so each component has one counted seed, then change ownership or reduce component area.

Published · 15 min read ·Core ·Intermediate

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Count new component seeds and mark each whole region

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A rectangular grid of independent mutable rows containing string cells "1" for land and "0" for water. Output. Return the number of connected land regions, not the number of land cells. Rules. Land connects only through up, down, left, and right neighbors, not diagonally. The reference consumes land by changing visited "1" cells to "0". Use strings rather than integer cells. Empty input returns zero. Example. Build rows with [list(row) for row in ["1100", "0101", "1001", "1011"]]: 1100 0101 1001 1011 Return 3, not the nine land cells. The reference leaves this grid containing only water.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Count each unseen land seed once, then erase its entire four-neighbor component with DFS.

Problem trace

Mark each land cell before scheduling its neighbors

Input and goalCount connected groups of land in a grid.
Start island 1Mark (0,0) as water before pushing it. This seed starts island 1.
0DFS top100010110011011
input4x4 grid; 4-neighbor land onlystack[(0,0)]islands1
DFS top
(0, 0)
input
4x4 grid; 4-neighbor land only
stack
[(0,0)]

Recognize it
The task asks for connected groups in a binary grid under four-direction adjacency, so every unseen land cell identifies exactly one not-yet-counted component.
Keep true
Before the scan advances, every visited land cell has been changed to 0; each stack contains only cells from the current island, and each completed island can never be counted again.
Reuse it
For regions, blobs, and connected-component problems, scan for unseen seeds, count seeds rather than cells, and exhaustively mark each seed’s reachable component before continuing.
Mark (0,0) as water before pushing it. This seed starts island 1. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which three original regions produced the count? Why does marking before pushing prevent duplicate work?
Full interview answer 15 min read

Count separate islands of land in a rectangular grid where only side-sharing cells are connected.

Problem

Input. A rectangular grid of independent mutable rows containing string cells "1" for land and "0" for water.

Output. Return the number of connected land regions, not the number of land cells.

Rules. Land connects only through up, down, left, and right neighbors, not diagonally. The reference consumes land by changing visited "1" cells to "0". Use strings rather than integer cells. Empty input returns zero.

Example. Build rows with [list(row) for row in ["1100", "0101", "1001", "1011"]]:

1100
0101
1001
1011

Return 3, not the nine land cells. The reference leaves this grid containing only water.

Picture

Imagine covering an entire connected patch when its first uncovered cell is found. Later scan positions inside that patch cannot start another island.

First unseen seedComponent cellsRunning count
(0,0)31
(1,3)42
(2,0)23

Problem trace

Separate shared-cell case: mark before scheduling a second discovery

Worked example: mark a discovered cell before another neighbor discovers it againFrom the top-left cell, two neighbors share the bottom-right cell. Marking on discovery puts that shared cell into the traversal once.Both neighbors reach one shared cell,not two copies of it1111marked (1,1)After A discovers the shared cellB1,1After B: shared cell was alreadymarked1,1The shared cell enters the queue oncebecause its mark precedes the seconddiscovery.
Read it this way: From the top-left cell, two neighbors share the bottom-right cell. Marking on discovery puts that shared cell into the traversal once. Would marking only when the shared cell is popped stop both earlier neighbors from enqueueing it?
Reference drawing

Problem trace

Mark each land cell before scheduling its neighbors

Worked example: mark a discovered cell before another neighbor discovers it againFrom the top-left cell, two neighbors share the bottom-right cell. Marking on discovery puts that shared cell into the traversal once.Both neighbors reach one shared cell,not two copies of it1111marked (1,1)After A discovers the shared cellB1,1After B: shared cell was alreadymarked1,1The shared cell enters the queue oncebecause its mark precedes the seconddiscovery.
Execution trace
Input and goalCount connected groups of land in a grid.
Start island 1Mark (0,0) as water before pushing it. This seed starts island 1.
0DFS top100010110011011
input4x4 grid; 4-neighbor land onlystack[(0,0)]islands1
DFS top
(0, 0)
input
4x4 grid; 4-neighbor land only
stack
[(0,0)]

Recognize it
The task asks for connected groups in a binary grid under four-direction adjacency, so every unseen land cell identifies exactly one not-yet-counted component.
Keep true
Before the scan advances, every visited land cell has been changed to 0; each stack contains only cells from the current island, and each completed island can never be counted again.
Reuse it
For regions, blobs, and connected-component problems, scan for unseen seeds, count seeds rather than cells, and exhaustively mark each seed’s reachable component before continuing.
Mark (0,0) as water before pushing it. This seed starts island 1. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Which three original regions produced the count? Why does marking before pushing prevent duplicate work?
Read it this way: From the top-left cell, two neighbors share the bottom-right cell. Marking on discovery puts that shared cell into the traversal once. Would marking only when the shared cell is popped stop both earlier neighbors from enqueueing it?

Mark a seed before placing it on the stack. Mark each new neighbor before pushing it, too. Every land cell is therefore scheduled once, even when several neighbors could discover it. Stack order changes visitation order, not component membership.

Code

def num_islands(grid: list[list[str]]) -> int:
   islands = 0

   for row in range(len(grid)):
      for col in range(len(grid[0])):
         if grid[row][col] != "1":
            continue

         islands += 1
         grid[row][col] = "0"
         stack = [(row, col)]
         while stack:
            current_row, current_col = stack.pop()
            for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
               new_row = current_row + row_step
               new_col = current_col + col_step
               if 0 <= new_row < len(grid) and 0 <= new_col < len(grid[0]):
                  if grid[new_row][new_col] == "1":
                     grid[new_row][new_col] = "0"
                     stack.append((new_row, new_col))

   return islands

Scanning and coverage take time. The explicit stack can require auxiliary space. There is no logarithmic-stack guarantee. Empty and zero-width grids return 0.

Failure Check

The diagonal grid ["10","01"] has two islands under this adjacency rule. Counting each popped cell returns area, not island count. Restoring marks would allow later scan positions to count the same component again.

Change the Ownership

New task: Count islands without changing the caller’s grid.

Picture and change: Copy each row before destructive coverage. The wrapper also accepts string rows by converting them to mutable character lists.

def islands_preserving(grid):
   return num_islands([list(row) for row in grid])

Check: The source still returns 3, with all original cells unchanged. The copy adds storage.

Use when: Mutation permission changes, not connectivity.

Change the Reduction

New task: Return the largest island area.

Picture and change: Keep permanent discovery marks, count cells within each completed flood, then maximize those counts. This version still consumes mutable string-cell rows.

def largest_island_area(grid):
   best = 0
   for row in range(len(grid)):
      for col in range(len(grid[0])):
         if grid[row][col] != "1":
            continue
         grid[row][col] = "0"
         stack, area = [(row, col)], 0
         while stack:
            current_row, current_col = stack.pop()
            area += 1
            for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
               next_row, next_col = current_row + row_step, current_col + col_step
               if 0 <= next_row < len(grid) and 0 <= next_col < len(grid[0]):
                  if grid[next_row][next_col] == "1":
                     grid[next_row][next_col] = "0"
                     stack.append((next_row, next_col))
         best = max(best, area)
   return best

Check: Source component areas are 3,4,2, so return 4. No land returns 0. Time and worst-case stack bounds remain unchanged.

Use when: Component size, not the number of components, is requested.

Transfer Check

Why keep marks permanently here but undo used-cell marks in a word-search branch?

Answer

Component membership is a global completed fact. A candidate path’s used cells constrain only that path; other paths must be allowed to try them again. Compare reversed reachability when the task asks which goals each cell can reach.