KatInterview

Tallest Staircase Walk Across a Number Board

Dynamic ProgrammingAuto-graded · 21 test cases
MediumAuto-gradedDynamic Programmingdynamic-programminggraphdfs

Last updated

Find the longest chain of orthogonally adjacent cells with strictly increasing values in a 2D grid, testing DAG longest-path DP, memoization, and avoiding deep recursion.

Tallest Staircase Walk Across a Number Board

You are given a rectangular board of integers, stored as a list of rows. A staircase walk starts on any cell and repeatedly moves to one of the four orthogonally adjacent cells (up, down, left, right). Every move must land on a cell whose value is strictly greater than the value of the cell you are leaving. Moves cannot leave the board, and diagonal moves are not allowed.

The length of a walk is the number of cells it visits, including the starting cell. A walk consisting of a single cell has length 1.

Return the length of the longest staircase walk that exists anywhere on the board.

Rules and edge cases

  • If the board has no rows, or its first row is empty, return 0.
  • Equal values never form a step, because the comparison must be strictly greater.
  • Values may be negative or repeated.
  • The board may be large, and a valid walk can pass through a very large number of cells, so be careful with recursion depth in your language.

Constraints

  • The board has m rows and n columns, with 0 <= m, n; all rows have the same length.
  • Each value is an integer that fits in a standard 32-bit signed integer.
  • Aim for a solution that runs in O(m * n) time (an O(m * n * log(m * n)) approach is also acceptable for small boards).
  • The function receives the board and returns a single integer.

Examples

Example 1

Input: longest_staircase_walk([[9, 9, 4], [6, 6, 8], [2, 1, 1]])

Output: 4

Example 2

Input: longest_staircase_walk([[3, 4, 5], [3, 2, 6], [2, 2, 1]])

Output: 4

Example 3

Input: longest_staircase_walk([[1]])

Output: 1

Hints

Hint 1

Draw an arrow from each cell to every neighbor with a strictly larger value. Can this graph contain a cycle? What does that imply about how to compute longest paths?

Hint 2

Let best[cell] be the longest walk that starts at that cell. It equals 1 plus the maximum best[] among strictly larger neighbors (or just 1 if there are none). Cache each result so every cell is computed once.

Hint 3

Deep recursion can be a problem on huge boards. Consider an explicit stack, processing cells in descending value order, or peeling off layers of cells with no larger neighbor (Kahn-style) and counting the layers.