InterviewPrepKit

Home / Coding / Algorithm & Data Structure / 2-D Dynamic Programming

Longest Increasing Path in a Matrix

hard Original ↗ 00:00

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).

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug