Find the Longest Momentum-Aware Water Path
Company: Google
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Solve a small-grid path problem where water may move to an equal or lower height, while an uphill step depends on the height two positions earlier. Find the longest non-repeating path from any starting cell while handling negative values, equal heights, and momentum-dependent state.
Read the full Google Software Engineer interview experience this question came from
Constraints
- 1 <= rows, columns <= 4
- rows * columns <= 15
- -10^9 <= heights[r][c] <= 10^9
- A path uses four-directional moves and never revisits a cell.
- The first move must be to an equal or lower height.
Examples
Input: ([[1]],)
Expected Output: 1
Explanation: A one-cell path is valid.
Input: ([[1, 1]],)
Expected Output: 2
Explanation: An equal-height first move is allowed.
Hints
- A state needs the visited mask, the current cell, and the preceding cell that supplies possible momentum.
- Memoize the best suffix length for each state; the 15-cell bound makes bitmasks practical.
Community answers
Answer by weian60333