TRT
Sign in
hardAdvancedLeetCode#memoized DFS#DAG longest path

Longest increasing path in a matrix

Find the longest strictly increasing path between neighboring cells of a grid with a memoized depth-first search.

The Runtime Theory Team1 min read
Taught inMemoizationPro — members onlyWhen a recursion solves the same subproblem many times, store each answer the first time and look it up after that. The cost becomes the number of distinct subproblems times the work for each.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inmatrix = [[9, 9, 4], [6, 6, 8], [2, 1, 1]]

out4

inmatrix = [[3, 4, 5], [3, 2, 6], [2, 2, 1]]

out4

inmatrix = [[1]]

out1

Return the length of the longest path in the matrix where each step moves to an adjacent cell (up, down, left, right) with a strictly larger value.

Before you code

The longest path starting at a cell is the same no matter how you reached it, and strictly increasing paths can't loop. So the answer for each cell can be computed once and reused.

Hints

  1. longest(r, c) = 1 + max(longest(nr, nc)) over neighbors with larger values, or 1 if none.
  2. Memoize on (r, c). Each cell is computed once: O(R × C).
  3. No visited set is needed: increasing values rule out cycles.

Production & complexity notes

When solving Longest increasing path in a matrix on LeetCode (hard), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Memoization to reinforce the underlying pattern.

What it practices

Memoizing a search on a directed acyclic graph, from Memoization.

Not started

Sign in to save your learning progress.

Sign in to save