Longest water-flow path with momentum
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Google's onsite coding round, last asked Apr 2026. It tests dynamic programming, grids and dfs.
You get a small m x n grid of heights. Water starts at any cell and moves up, down, left or right, never visiting a cell twice. Going downhill or level is always allowed. Going uphill is allowed only with momentum: the height two cells back on the path must be at least as high as the cell being entered. Return the largest number of cells on a valid path.
Interface
Unless you agree on a different interface with the interviewer, assume:
longest_flow(heights: list[list[int]]) -> int
For consecutive path heights ..., a, b, c, where b is the current cell and c the next one, the move from b to c is valid when:
-
c <= b(level or downhill), or -
c > banda >= c(the height two positions back supplies the momentum).
The first move has no a, so it must be level or downhill. A path of one cell is valid.
Example
longest_flow([[5, 1, 4]]) -> 3 # 5 -> 1 -> 4: the uphill step to 4 uses the 5
longest_flow([[1]]) -> 1
longest_flow([[1, 1]]) -> 2 # a level first move is allowed
longest_flow([[3, 1],
[2, 5]]) -> 4 # 5 -> 1 -> 3 -> 2
Constraints
-
1 <= m, n <= 4andm * n <= 15. - Heights are in
[-10^9, 10^9]; equal and negative heights are possible.
Clarifying questions
- Does momentum come only from the cell two steps back, or from the highest point so far?
- Is the uphill condition
a >= cora > c? - Can the path revisit a cell?
- Why is the grid so small? (It signals that exponential search over visited sets is expected.)
What a strong answer covers
- The state a move depends on: the current cell, the previous cell and the set of visited cells.
- Backtracking DFS from every start cell with a visited bitmask; with at most 15 cells this is fast enough.
- Memoisation on
(mask, previous, current)to avoid repeating work: at most2^15 * 15 * 4states. - Getting the first move right (no momentum yet) and the boundary on equal heights.
- Tests: single cell, all equal heights, strictly increasing row (answer is the length when walked downhill), negative values.
Follow-ups
- Momentum comes from the highest cell seen so far on the path instead of two cells back.
- The grid is 100 x 100. Why does the search blow up, and which change to the rules (for example strictly downhill moves only) makes a DP over cells possible?
- Return the path, not only its length.
Where it's asked
- Google · Onsite coding · Last asked Apr 202645 min · Usually two rounds, mostly in person: whiteboard plus a Chromebook with Google Docs · No AI (a pilot code-comprehension round lets candidates use Gemini)
What it tests
dynamic programming · grids · dfs
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
