← Questions

Cells water reaches flowing downhill

0
AmazonCodingLast asked Oct 2025

A coding interview question asked in Amazon's technical phone screen, last asked Oct 2025. It tests dfs, bfs and grids.

A 2D map gives the height of each cell. A drop of water lands on a starting cell and flows from a cell to any of its four neighbours (up, down, left, right) whose height is strictly lower. Return every cell the water can reach, the starting cell included.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • wet_cells(heights: list[list[int]], start: tuple[int, int]) -> list[tuple[int, int]] — sorted by row, then column.

Example

heights = [[5, 4, 3],
           [6, 1, 2],
           [7, 8, 9]]
wet_cells(heights, (0, 0))  ->  [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2)]
# 5 -> 4 -> 3 -> 2, and 4 -> 1; the 6, 7, 8, 9 cells are higher and stay dry

heights = [[1, 2, 3],
           [8, 9, 4],
           [7, 6, 5]]
wet_cells(heights, (1, 1))  ->  all nine cells    # from the 9, paths step down to every cell

wet_cells([[3, 3], [3, 1]], (0, 0))  ->  [(0, 0)]
# equal heights block the flow, and the 1 is only diagonal

Constraints

  • m and n up to a few thousand, so aim for time linear in the grid size.
  • Heights are any integers and may repeat.

Clarifying questions

  • Strictly lower, or lower or equal? (Strictly lower.)
  • Are diagonal moves allowed? (No.)
  • Should the result be sorted?

What a strong answer covers

  • A breadth-first or depth-first flood fill from the start that only steps to strictly lower neighbours: each cell is visited at most once, O(m · n) time and space.
  • Iterative traversal rather than recursion, which would overflow the stack on a large grid.
  • Why the "lower or equal" variant needs a visited set to avoid cycling among equal heights.
  • The relation to the "which cells drain to both oceans" problem, which runs the same search backwards (uphill) from the edges.

Follow-ups

  • Water also flows to neighbours of equal height. What changes?
  • Find every cell from which water reaches the top or left edge and also the bottom or right edge.
  • Answer many start cells quickly.

Where it's asked

  • Amazon · Technical phone screen · Last asked Oct 202560 min · Live coding in a shared editor that does not run code, plus Leadership Principles questions · No AI

What it tests

dfs · bfs · grids

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding