Longest Increasing Path in a Matrix solution explained
The longest increasing path in a matrix is the longest chain of cells, moving up, down, left or right, where each step goes to a strictly larger value. Because values must strictly increase, a path can never loop, so the moves form a directed acyclic graph and the longest path from each cell can be memoized: best(cell) = 1 + the largest best over its larger neighbours. That gives O(m · n) time for an m by n matrix. Processing cells from highest to lowest value, or peeling local minima layer by layer, reaches the same answer without deep recursion.
By Evin JohnPublished 8 min read
Restating the problem
You get a matrix of integers with m rows and n columns. A path moves from a cell to one of its four neighbours, never diagonally and never off the edge, and every step must go to a strictly larger value. Return the number of cells on the longest such path. Every single cell is a path of length 1, so the answer is at least 1 for any non-empty matrix.
| Matrix | Answer | One longest path |
|---|---|---|
| 3 4 5 / 3 2 6 / 2 2 1 | 4 | 3, 4, 5, 6 along the top and down the right |
| 1 2 3 / 8 9 4 / 7 6 5 | 9 | The spiral 1 to 9 uses every cell |
| 7 | 1 | A single cell |
| 5 5 / 5 5 | 1 | Equal neighbours do not count as increasing |
What it checks
Longest simple path is a hard problem on general graphs, and a candidate who knows that may freeze. The insight the interviewer wants is that strict increase rules out cycles: you can never come back to a cell, because its value would have to be larger than itself. On an acyclic graph, the longest path from a node depends only on its successors, so memoization works and the problem becomes linear in the number of cells. Saying this clearly is most of the answer.
Brute force
From every cell, run a DFS that tries every increasing neighbour and returns the longest path found. No visited set is needed, since a path cannot revisit a cell. The trouble is that the same cell is explored again for every path that reaches it, which can be exponential on matrices with many branching increasing routes. It is a fine reference for testing and a natural first sentence in the interview.
Memoized DFS
Cache the result per cell. The first time best(r, c) is asked for, compute 1 plus the largest best among the larger neighbours, store it, and return it. Every later request is a lookup. Each cell is computed once and checks four neighbours, so the total work is O(m · n). The answer is the largest best over all cells.
#include <algorithm>
#include <vector>
using namespace std;
class LongestPath {
const vector<vector<int>>& m;
int rows, cols;
vector<vector<int>> memo; // 0 = not computed yet
int from(int r, int c) {
if (memo[r][c]) return memo[r][c];
static const int dr[4] = {1, -1, 0, 0};
static const int dc[4] = {0, 0, 1, -1};
int best = 1;
for (int k = 0; k < 4; k++) {
int nr = r + dr[k], nc = c + dc[k];
if (nr >= 0 && nr < rows && nc >= 0 && nc < cols && m[nr][nc] > m[r][c]) {
best = max(best, 1 + from(nr, nc));
}
}
return memo[r][c] = best;
}
public:
explicit LongestPath(const vector<vector<int>>& matrix)
: m(matrix), rows(matrix.size()), cols(matrix.empty() ? 0 : matrix[0].size()),
memo(rows, vector<int>(cols, 0)) {}
int solve() {
int answer = 0;
for (int r = 0; r < rows; r++)
for (int c = 0; c < cols; c++) answer = max(answer, from(r, c));
return answer;
}
};A memo value of 0 means not computed yet, which is safe because every real answer is at least 1. The recursion can go as deep as the longest path, which is m · n on a snake-shaped matrix. The C++ version handled a 200 by 200 snake (depth 40,000) in testing, but default stack sizes vary by platform, so mention the risk. In Python, recursion that deep fails at the default limit, which is why the Python versions below are iterative.
Iterative: fill cells from the highest value down
best(r, c) only depends on neighbours with larger values. So if you process cells in decreasing order of value, every neighbour you need is already final when you reach a cell. Sort the cells, then make one pass. Equal values never depend on each other, so ties can come in any order. The sort makes this O(mn log mn), slightly more than the memoized DFS, but there is no recursion at all.
def longest_increasing_path(matrix):
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
best = [[1] * cols for _ in range(rows)] # longest path starting at each cell
cells = sorted(((matrix[r][c], r, c) for r in range(rows) for c in range(cols)), reverse=True)
for value, r, c in cells: # higher cells are finished first
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > value:
best[r][c] = max(best[r][c], 1 + best[nr][nc])
return max(max(row) for row in best)On the first matrix, the 6 is processed first and gets 1. The 5 next to it gets 2, the 4 gets 3, and the 3 in the top-left corner gets 4. The 2 in the middle also reaches 4, through 4, 5 and 6. No cell does better, so the answer is 4.
Iterative: peel the DAG in layers
The second iterative approach is topological sort in rounds. Count, for every cell, how many smaller neighbours it has; cells with none are local minima and form the first layer. Remove a layer, lower the counts of the larger neighbours of its cells, and collect the cells whose count reaches zero as the next layer. The number of layers equals the number of cells on the longest increasing path, because each layer extends the longest chain by exactly one.
def longest_increasing_path_layers(matrix):
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
lower = [[0] * cols for _ in range(rows)] # how many smaller neighbours each cell has
for r in range(rows):
for c in range(cols):
for dr, dc in dirs:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] < matrix[r][c]:
lower[r][c] += 1
layer = [(r, c) for r in range(rows) for c in range(cols) if lower[r][c] == 0]
length = 0
while layer: # peel local minima, Kahn's style
length += 1
nxt = []
for r, c in layer:
for dr, dc in dirs:
nr, nc = r + dr, c + dc
if 0 <= nr < rows and 0 <= nc < cols and matrix[nr][nc] > matrix[r][c]:
lower[nr][nc] -= 1
if lower[nr][nc] == 0:
nxt.append((nr, nc))
layer = nxt
return lengthThis is the only version with linear time and no recursion, at the price of an extra count matrix. It is also a nice way to show the interviewer that you recognised the hidden DAG, not just a caching trick.
Complexity
| Approach | Time | Extra space |
|---|---|---|
| DFS from every cell, no memo | Exponential in the worst case | O(m · n) stack |
| Memoized DFS | O(m · n) | O(m · n) memo, plus recursion up to m · n deep |
| Sort by value, then DP | O(mn log mn) | O(m · n) |
| Kahn's layers | O(m · n) | O(m · n) |
Edge cases
- A 1 by 1 matrix: 1.
- All values equal: 1, because steps must strictly increase.
- A single row or column.
- A snake-shaped increasing path through every cell: deep recursion.
- Negative values, which change nothing.
- An empty matrix, if allowed: return 0.
Mistakes
- Allowing equal neighbours, which creates cycles and wrong answers.
- Adding a visited set on top of the memo, which is unnecessary and can block valid reuse if done wrongly.
- Starting the search only from the top-left cell instead of every cell.
- Using 0 as both not-computed and a real result in a language where a path could be 0 long.
- Recursive Python on large inputs without considering the recursion limit.
- Counting moves instead of cells.
How to explain it out loud
Fictional example
- Candidate
- Longest path is usually hard, but here every step must go to a strictly larger value, so a path can never return to a cell. The moves form a DAG.
- Candidate
- On a DAG, the longest path from a cell is one plus the best of its larger neighbours, so I'll memoize that per cell and take the maximum over all cells.
- Interviewer
- Any concern with recursion?
- Candidate
- The depth can reach the number of cells on a snake-shaped input. If that's an issue, I'd process cells from the largest value down, or peel layers from the local minima, which is Kahn's algorithm. Both avoid recursion.
Related problems
The layer method is topological sort in rounds, and the memo per position is the same idea as in Word Break II. For grid traversal without the increasing rule, see Number of Islands and Swim in Rising Water. The next problems in this set are Range Sum Query and Number of Provinces.
Practicing it with Natively
Seeing three correct versions side by side helps this problem stick. Natively can read the matrix problem from a screenshot on Mac or Windows and set out an approach and code in its overlay, so you can check whether your memo and base case match. In a mock interview spoken aloud, the transcript it keeps lets you confirm you explained why there are no cycles. See the AI interview assistant.
Questions people ask
How do you solve Longest Increasing Path in a Matrix?
Memoize, for each cell, 1 plus the longest path from any larger neighbour, and take the maximum over all cells. Each cell is computed once, so it runs in O(m · n).
Why doesn't Longest Increasing Path need a visited set?
Values must strictly increase, so a path can never return to a cell it already used. The moves form a directed acyclic graph.
Can Longest Increasing Path in a Matrix be solved without recursion?
Yes. Process cells from the highest value down, or peel local minima layer by layer with Kahn's algorithm; the number of layers is the answer.
What is the time complexity of Longest Increasing Path in a Matrix?
O(m · n) with memoized DFS or Kahn's layers, and O(mn log mn) if you sort the cells by value first.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
