InterviewPrepKit

Home / Coding / 2-D Dynamic Programming

Longest Increasing Path in a Matrix

hard Original ↗
Solving tips
  • Define dp[i][j] = longest increasing path STARTING at (i,j) = 1 + max over strictly-larger neighbors; the global answer is the max over all cells.
  • Key insight: strict increase means the dependency graph is a DAG (no cycles), so memoized DFS is safe and no visited-set is needed.
  • Target O(m*n) time and space, since each cell is computed exactly once with O(1) neighbor work.
  • Pitfalls: using >= instead of strict > (creates cycles / non-increasing paths), and counting edges instead of cells (a single cell is length 1, not 0). The topological-peel (Kahn) variant avoids recursion-depth limits.

Problem

Given an m × n integer matrix, find the length of the longest path along which values strictly increase. From a cell you may move to any of its four orthogonal neighbors (up, down, left, right); diagonal moves and wrap-around are not allowed. The path length is the number of cells it visits.

Because values must strictly increase, a path can never revisit a cell, so no explicit visited-set is needed.

Examples

  • matrix = [[9,9,4],[6,6,8],[2,1,1]]4 — the path 1 → 2 → 6 → 9 (bottom-up along the left) has 4 cells.
  • matrix = [[3,4,5],[3,2,6],[2,2,1]]4 — the path 3 → 4 → 5 → 6 has 4 cells; diagonal moves are disallowed.
  • matrix = [[1]]1 — a single cell is a path of length 1.

Constraints

  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1
  • A 200×200 grid has 40,000 cells; an O(m·n) method is expected. Naive path enumeration is exponential.

Think about it first

Hint 1 Define the answer per starting cell: the longest increasing path that *begins* at `(i, j)`. The global answer is the maximum of that over all cells.
Hint 2 From `(i, j)` you can step only to a strictly larger neighbor. So the longest path starting at `(i, j)` is `1 + max(longest path starting at each larger neighbor)`. Strict increase means these subproblems form a DAG with no cycles — so a plain recursion terminates, and results can be cached.
Hint 3 Memoize `dp[i][j]` = longest increasing path starting at `(i, j)`. Each cell is computed once; its value reuses already-cached larger neighbors. Alternatively, treat cells as DAG nodes and peel them off in a topological order (process the largest values first, or shrink outdegrees like Kahn's algorithm).
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.