Skip to content
mlmentorship

Longest Increasing Path in a Matrix

Use strict value growth to justify a coordinate-only suffix cache, then change evaluation order to avoid recursion or count all increasing paths.

Published · 17 min read ·Specialist ·Advanced

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

Longest Increasing Path in a Matrix

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

Problem

Input. A rectangular integer matrix, possibly empty. Output. Return the maximum number of cells in a path whose value strictly increases at every move. Rules. Start at any cell and move only up, down, left, or right within the matrix. Diagonal moves and equal-valued moves are forbidden. Count cells, not edges, and preserve the matrix. Empty input returns zero. Example. For [[9, 9, 4], [6, 6, 8], [2, 1, 1]], return 4. One path follows values 1 -> 2 -> 6 -> 9 through adjacent cells.

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

Treat larger-neighbor moves as a DAG, recursively solve each cell once, and memoize the longest suffix length returned to its predecessors.

Problem trace

Cache each increasing suffix so later starting points can reuse it

Worked example: a cached suffix can serve more than one starting pointIn this illustrative grid, starts one and two both reach the same adjacent suffix 3,4. Its length two is cached at cell three and reused.Two starts enter the same adjacentincreasing suffix134020Cache at cell three: suffix lengthtwo for route 3,4.Reuse that cell-owned answer fromeither start. The two copies of theroute are not separate subproblems.
Read it this way: In this illustrative grid, starts one and two both reach the same adjacent suffix 3,4. Its length two is cached at cell three and reused. Does the memoized suffix length at three depend on whether the entry route started at one or two?
Full interview answer 17 min read

Find the longest strictly increasing route through orthogonally adjacent cells in a matrix.

Problem

Input. A rectangular integer matrix, possibly empty.

Output. Return the maximum number of cells in a path whose value strictly increases at every move.

Rules. Start at any cell and move only up, down, left, or right within the matrix. Diagonal moves and equal-valued moves are forbidden. Count cells, not edges, and preserve the matrix. Empty input returns zero.

Example. For [[9, 9, 4], [6, 6, 8], [2, 1, 1]], return 4. One path follows values 1 -> 2 -> 6 -> 9 through adjacent cells.

Picture

For [[3,4,5],[2,1,6]], draw an arrow from each cell to each larger orthogonal neighbor. The longest route follows values 1,2,3,4,5,6, using six distinct cells.

A cycle would require strict increases back to the starting value, making that value larger than itself. Thus no path-local visited set is needed. A continuation cannot revisit its caller’s smaller-valued prefix.

Define as the longest increasing path starting at coordinate , including that cell. A peak returns one. Otherwise choose the largest among its larger neighbors.

Completed returnCached lengthReason
(1,2), value 61No larger neighbor
(0,2), value 52One plus 6’s suffix
(0,1), value 43One plus 5’s suffix
(0,0), value 34One plus 4’s suffix
(1,0), value 25Reuse 3’s completed suffix
(1,1), value 16Best among neighbors 4, 6 and 2

The memo becomes [[4,3,2],[5,6,1]]. A cached value means a completed answer, not merely a discovered cell. Global flood-fill marks would wrongly suppress valid reuse by other callers.

Coordinate alone identifies the suffix because the immutable matrix fixes every legal continuation. Create the cache inside each call. Sharing it across changed matrices would reuse answers from the wrong graph.

Equal-valued neighbors have no edge. Changing > to >= permits cycles and invalidates this reasoning.

Problem trace

Cache each increasing suffix so later starting points can reuse it

Input and goalFind the longest path that moves to a larger neighboring value each step.
Start DFS at value 3The outer max begins at (0,0)=3. Only larger neighbor 4 can extend this path.
345216
completed0
Original matrix and DFS cursor
3DFS cursor45216
memo[.,.,.; .,.,.]dependency3 -> 4bestpath_from(0,0) starts at 1
DFS cursor
(0, 0)
memo
[.,.,.; .,.,.]
dependency
3 -> 4

Recognize it
Use memoized DFS when every cell asks for an optimal path through neighboring states and a strict monotone move rule prevents cycles.
Keep true
Once path_from(r,c) returns, its memo value is the longest increasing path starting at that cell; every candidate is 1 plus an already correct recursively computed larger-neighbor suffix.
Reuse it
A strict ranking function can turn implicit neighbor moves into a DAG; memoize the optimal suffix at each state and combine it from higher-ranked neighbors.
The outer max begins at (0,0)=3. Only larger neighbor 4 can extend this path. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can the result cached at value 3 be reused from value 2 without exploring the suffix again?
Reference drawing

Problem trace

Cache each increasing suffix so later starting points can reuse it

Worked example: a cached suffix can serve more than one starting pointIn this illustrative grid, starts one and two both reach the same adjacent suffix 3,4. Its length two is cached at cell three and reused.Two starts enter the same adjacentincreasing suffix134020Cache at cell three: suffix lengthtwo for route 3,4.Reuse that cell-owned answer fromeither start. The two copies of theroute are not separate subproblems.
Execution trace
Input and goalFind the longest path that moves to a larger neighboring value each step.
Start DFS at value 3The outer max begins at (0,0)=3. Only larger neighbor 4 can extend this path.
345216
completed0
Original matrix and DFS cursor
3DFS cursor45216
memo[.,.,.; .,.,.]dependency3 -> 4bestpath_from(0,0) starts at 1
DFS cursor
(0, 0)
memo
[.,.,.; .,.,.]
dependency
3 -> 4

Recognize it
Use memoized DFS when every cell asks for an optimal path through neighboring states and a strict monotone move rule prevents cycles.
Keep true
Once path_from(r,c) returns, its memo value is the longest increasing path starting at that cell; every candidate is 1 plus an already correct recursively computed larger-neighbor suffix.
Reuse it
A strict ranking function can turn implicit neighbor moves into a DAG; memoize the optimal suffix at each state and combine it from higher-ranked neighbors.
The outer max begins at (0,0)=3. Only larger neighbor 4 can extend this path. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why can the result cached at value 3 be reused from value 2 without exploring the suffix again?
Read it this way: In this illustrative grid, starts one and two both reach the same adjacent suffix 3,4. Its length two is cached at cell three and reused. Does the memoized suffix length at three depend on whether the entry route started at one or two?

Code

from functools import cache

def longest_increasing_path(matrix: list[list[int]]) -> int:
   if not matrix or not matrix[0]:
      return 0

   @cache
   def path_from(row: int, col: int) -> int:
      best = 1
      for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
         new_row = row + row_step
         new_col = col + col_step
         if 0 <= new_row < len(matrix) and 0 <= new_col < len(matrix[0]):
            if matrix[new_row][new_col] > matrix[row][col]:
               best = max(best, 1 + path_from(new_row, new_col))
      return best

   return max(
      path_from(row, col)
      for row in range(len(matrix))
      for col in range(len(matrix[0]))
   )

Cost: time and space.

Each coordinate computes once and checks four neighbors. Cache size and maximum recursive depth can both reach . Python can raise RecursionError on a long valid chain; linear total work does not prevent that failure.

Change Evaluation or Aggregation

Start from longest_increasing_path. Preserve strict growth while changing how completed states are obtained or combined.

  1. Avoid recursive depth.

    New task: Support increasing chains longer than Python’s call-stack limit.

    Picture and change: Count incoming edges from smaller neighbors. Use zero-indegree elimination in frozen batches. A cell becomes ready after its last predecessor, so its layer is one plus the maximum predecessor layer. This measures length ending there; the global maximum matches the source’s starting-length maximum.

    Code: Complete replacement:

    from collections import deque
    
    
    def increasing_path_layers(matrix):
       if not matrix or not matrix[0]:
          return 0
       rows, columns = len(matrix), len(matrix[0])
       steps = ((1, 0), (-1, 0), (0, 1), (0, -1))
       degree = [[0] * columns for _ in range(rows)]
       for row in range(rows):
          for column in range(columns):
             degree[row][column] = sum(
                0 <= row + row_step < rows
                and 0 <= column + col_step < columns
                and matrix[row + row_step][column + col_step] < matrix[row][column]
                for row_step, col_step in steps
             )
       frontier = deque(
          (row, column)
          for row in range(rows)
          for column in range(columns)
          if degree[row][column] == 0
       )
       layers = 0
       while frontier:
          layers += 1
          for _ in range(len(frontier)):
             row, column = frontier.popleft()
             for row_step, col_step in steps:
                new_row, new_col = row + row_step, column + col_step
                if 0 <= new_row < rows and 0 <= new_col < columns:
                   if matrix[new_row][new_col] > matrix[row][column]:
                      degree[new_row][new_col] -= 1
                      if degree[new_row][new_col] == 0:
                         frontier.append((new_row, new_col))
       return layers

    Check: The six-cell example returns six. [[1,1]] returns one, not two.

    Use when: Recursion depth is a risk. Work and degree/frontier storage remain without recursive calls.

  2. Count every increasing path.

    New task: Count all nonempty coordinate paths, not just the longest length.

    Picture and change: Process cells by increasing value. Each has one singleton path plus paths ending at its smaller neighbors. Sum those ending counts. Equal values create no dependency, regardless of their sorting order.

    Code: Complete replacement:

    def count_increasing_paths(matrix):
       if not matrix or not matrix[0]:
          return 0
       rows, columns = len(matrix), len(matrix[0])
       counts = [[0] * columns for _ in range(rows)]
       cells = sorted(
          (matrix[row][column], row, column)
          for row in range(rows)
          for column in range(columns)
       )
       for value, row, column in cells:
          counts[row][column] = 1
          for row_step, col_step in ((1, 0), (-1, 0), (0, 1), (0, -1)):
             new_row, new_col = row + row_step, column + col_step
             if 0 <= new_row < rows and 0 <= new_col < columns:
                if matrix[new_row][new_col] < value:
                   counts[row][column] += counts[new_row][new_col]
       return sum(map(sum, counts))

    Check: [[1,2]] has three paths: [1], [2], [1,2]. [[1,1]] has two singletons.

    Use when: Multiplicity replaces length. For , sorting costs ; storage is . Exact counts can grow large, so arithmetic cost also depends on integer bit lengths.

Rebuild State Sufficiency

Why can another caller reuse the same coordinate’s suffix?

Answer: Strict growth prevents reentering its smaller prefix. The unchanged matrix, not the caller’s route, determines every legal continuation.