329. Longest Increasing Path in a Matrix
hardReturn the length of the longest path of strictly increasing values in a matrix, where moves are to 4-directional neighbors. The strict-increase rule makes the path graph acyclic — that's what unlocks memoized DFS over the grid.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given an m x n integers matrix, return the length of the longest increasing path in matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).
Constraints
m == matrix.lengthn == matrix[i].length1 <= m, n <= 2000 <= matrix[i][j] <= 2^31 - 1
Examples
Example 1
matrix = [[9,9,4],[6,6,8],[2,1,1]]4Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2
matrix = [[3,4,5],[3,2,6],[2,2,1]]4Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Example 3
matrix = [[1]]1Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Strict increase means edges only go from smaller to larger — no cycles. Every cell has a well-defined longest path starting from it.
Hint 2
Memoize dfs(i, j) = 1 + max over strictly-larger neighbors of dfs(neighbor).
Hint 3
Iterate every cell, return the global max. Each cell is computed once.
Hint 4
Alternative: topological sort by cell value, then relax distances on the DAG — same big-O.
Solution approach
Reveal approach
Memoized DFS. dp[i][j] caches the length of the longest strictly-increasing path starting at (i, j). For each cell, recursively explore its four neighbors; recurse only into neighbors whose value is strictly greater. dp[i][j] = 1 + max over valid neighbors of dp[neighbor]. Iterate every starting cell and return the global max. Because strict increase forbids cycles, each cell is visited and memoized exactly once. An alternative is topological-order DP: sort all cells by value ascending, then relax each cell's two smaller-or-equal neighbors' dp into the cell. Both run in O(m * n) time and O(m * n) space.
Complexity
- Time
- O(m * n)
- Space
- O(m * n)
Related patterns
- dynamic-programming
- memoization
- grid-dp
- dfs
Related problems
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Apple
Practice these live with InterviewChamp.AI
Drill Longest Increasing Path in a Matrix and 2D Dynamic Programming problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →