Skip to content
mlmentorship

Reverse the edges when many starts share a few goals

Search uphill from each destination border, keep separate reachability certificates, and intersect them.

Published · 10 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

Reverse the edges when many starts share a few goals

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

Problem

Input. A rectangular integer height grid heights. Output. Return zero-based [row, col] coordinates of every cell with a route to each ocean. Rules. The Pacific touches the top and left borders; the Atlantic touches the bottom and right borders. Water moves to equal or lower orthogonal neighbors, never diagonally or uphill. The two routes may differ. Border cells already touch their corresponding ocean. Preserve the grid. Empty input returns []; the reference orders coordinates by row, then column. Example. For this grid: 1 2 2 3 2 3 2 4 1 Return [[0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1]]. This asks reachability, not water volume or travel time.

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

Reverse both flow searches from their ocean borders, move uphill, then intersect the reached cells.

Problem trace

Reverse search climbs to cells whose water can flow down to the ocean

Input and goalFind cells whose water can reach both oceans.
Seed the Pacific reverse searchSeed the Pacific search from every top and left border cell. These five seeds initialize both seen and the stack.
1P seed2P seed2P seed3P seed232P seed41
input3x3 heights; top/left=P, bottom/right=AsearchPacificstack5 border seedsreached5 cells
P seed
(0, 0)
P seed
(0, 1)
P seed
(0, 2)

Recognize it
Many grid cells ask whether they can reach either of two fixed boundary goals; reversing the edges lets each goal share one traversal across all possible starts.
Keep true
Each ocean’s seen set contains exactly cells with a nonincreasing forward path to that ocean. Reverse traversal may move only to an equal-or-higher neighbor, preserving that path witness.
Reuse it
When many sources query reachability to a small set of goals, reverse the graph, traverse once from each goal class, and combine the resulting reachable sets.
Seed the Pacific search from every top and left border cell. These five seeds initialize both seen and the stack. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why may reverse search move from height 2 to height 3? What does that prove about forward water flow?
Full interview answer 10 min read

Find all height-grid cells from which water can reach both of two opposite ocean borders.

Problem

Input. A rectangular integer height grid heights.

Output. Return zero-based [row, col] coordinates of every cell with a route to each ocean.

Rules. The Pacific touches the top and left borders; the Atlantic touches the bottom and right borders. Water moves to equal or lower orthogonal neighbors, never diagonally or uphill. The two routes may differ. Border cells already touch their corresponding ocean. Preserve the grid. Empty input returns []; the reference orders coordinates by row, then column.

Example. For this grid:

1 2 2
3 2 3
2 4 1

Return [[0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1]]. This asks reachability, not water volume or travel time.

Picture

Instead of searching from every cell, start at the destinations and walk backward along allowed edges. If high cell u can flow to neighbor v, the reverse search at v can reach u. Reverse movement therefore requires neighbor_height >= current_height.

For example, (1,1) -> (0,1) -> (0,2) is a forward level-height route to the Atlantic. Its reverse (0,2) -> (0,1) -> (1,1) certifies the same reachability.

Reverse searchReached cellsOnly missing cell
Pacific8(2,2)
Atlantic8(0,0)

Intersect the sets to retain exactly the cells with both certificates.

Problem trace

Reverse search climbs to cells whose water can flow down to the ocean

Worked example: reverse search walks uphill to find possible downhill sourcesStarting from an ocean, reverse traversal may move from height 2 to 5. Moving to height 1 reverses the intended reachability rule.Reverse source search moves to equalor higher heightsOcean-side two can reverse towardfive25Lower one cannot reverse towardocean-side two21The accepted reverse uphill edgecorresponds to water flowing downhillin the original direction.
Read it this way: Starting from an ocean, reverse traversal may move from height 2 to 5. Moving to height 1 reverses the intended reachability rule. Is an equal-height neighbor allowed by the reversed search, or must every step rise strictly?
Reference drawing

Problem trace

Reverse search climbs to cells whose water can flow down to the ocean

Worked example: reverse search walks uphill to find possible downhill sourcesStarting from an ocean, reverse traversal may move from height 2 to 5. Moving to height 1 reverses the intended reachability rule.Reverse source search moves to equalor higher heightsOcean-side two can reverse towardfive25Lower one cannot reverse towardocean-side two21The accepted reverse uphill edgecorresponds to water flowing downhillin the original direction.
Execution trace
Input and goalFind cells whose water can reach both oceans.
Seed the Pacific reverse searchSeed the Pacific search from every top and left border cell. These five seeds initialize both seen and the stack.
1P seed2P seed2P seed3P seed232P seed41
input3x3 heights; top/left=P, bottom/right=AsearchPacificstack5 border seedsreached5 cells
P seed
(0, 0)
P seed
(0, 1)
P seed
(0, 2)

Recognize it
Many grid cells ask whether they can reach either of two fixed boundary goals; reversing the edges lets each goal share one traversal across all possible starts.
Keep true
Each ocean’s seen set contains exactly cells with a nonincreasing forward path to that ocean. Reverse traversal may move only to an equal-or-higher neighbor, preserving that path witness.
Reuse it
When many sources query reachability to a small set of goals, reverse the graph, traverse once from each goal class, and combine the resulting reachable sets.
Seed the Pacific search from every top and left border cell. These five seeds initialize both seen and the stack. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why may reverse search move from height 2 to height 3? What does that prove about forward water flow?
Read it this way: Starting from an ocean, reverse traversal may move from height 2 to 5. Moving to height 1 reverses the intended reachability rule. Is an equal-height neighbor allowed by the reversed search, or must every step rise strictly?

Seed every border cell for an ocean before traversing. Mark on discovery so each cell enters that ocean’s stack once. Keep the oceans’ sets separate: one combined seed set would certify either, not both.

Code

def pacific_atlantic(heights: list[list[int]]) -> list[list[int]]:
   if not heights or not heights[0]:
      return []

   rows, cols = len(heights), len(heights[0])

   def reachable(starts: set[tuple[int, int]]) -> set[tuple[int, int]]:
      seen = set(starts)
      stack = list(starts)
      while stack:
         row, col = stack.pop()
         for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            next_cell = row + row_step, col + col_step
            next_row, next_col = next_cell
            if not (0 <= next_row < rows and 0 <= next_col < cols):
               continue
            if next_cell in seen or heights[next_row][next_col] < heights[row][col]:
               continue
            seen.add(next_cell)
            stack.append(next_cell)
      return seen

   pacific = {(row, 0) for row in range(rows)} | {(0, col) for col in range(cols)}
   atlantic = {(row, cols - 1) for row in range(rows)} | {
      (rows - 1, col) for col in range(cols)
   }
   return [list(cell) for cell in sorted(reachable(pacific) & reachable(atlantic))]

For , the searches use time and space without changing heights. The literal reference sorts its intersection cells. Whole-function time is therefore , not unconditionally linear. Empty or zero-width input returns [].

Failure Check

Searching downhill from the borders follows the wrong edges. Strictly uphill search also fails: equal-height plateau routes are allowed. One shared visited set cannot distinguish the two required destination classes.

Change the Goals

New task: Find cells that can flow to any member of an arbitrary valid goal set.

Picture and change: Reverse from those goals, then emit reached cells by row-major membership scan instead of sorting. Duplicate goals are coalesced; an empty goal set reaches nothing.

def reverse_reached_cells(heights, starts):
   if not heights or not heights[0]:
      return []
   rows, cols = len(heights), len(heights[0])
   seen = {tuple(cell) for cell in starts}
   stack = list(seen)
   while stack:
      row, col = stack.pop()
      for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
         next_row, next_col = row + row_step, col + col_step
         cell = next_row, next_col
         if 0 <= next_row < rows and 0 <= next_col < cols:
            if cell not in seen and heights[next_row][next_col] >= heights[row][col]:
               seen.add(cell)
               stack.append(cell)
   return [[row, col] for row in range(rows) for col in range(cols) if (row, col) in seen]

Check: [[1,2],[3,1]], goal (0,0), returns [[0,0],[0,1],[1,0]]. The lower-right basin cannot reach that goal. For supplied goals, time is and auxiliary space is . Heights remain unchanged.

Use when: Many origin cells share arbitrary destinations, including interior outlets.

Change Both to Either

New task: Reaching at least one ocean is sufficient.

Picture and change: Combine all border goals before one reverse traversal, computing a union rather than an intersection.

def reaches_either_ocean(heights):
   if not heights or not heights[0]:
      return []
   rows, cols = len(heights), len(heights[0])
   borders = (
      {(row, 0) for row in range(rows)}
      | {(row, cols - 1) for row in range(rows)}
      | {(0, col) for col in range(cols)}
      | {(rows - 1, col) for col in range(cols)}
   )
   return reverse_reached_cells(heights, borders)

Check: A 3x3 grid with border height 3 and center height 1 returns only its eight border cells. Either-ocean reachability does not include every basin. Time and space are , including deterministic row-major output.

Use when: The goal combination changes from AND to OR.

Transfer Check

What changes if three goal classes must each be reachable?

Answer

Run one reverse search per class, then intersect all three certificates. Merging their seeds would answer a different OR question.