← Questions
Longest increasing path in a matrix
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Apr 2026. It tests dfs, memoization and matrices.
Given an integer matrix, return the length of the longest path that moves up, down, left or right and only ever steps to a strictly larger value. A path's length is its number of cells. Avoid exponential search: each cell should be solved once.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
longest_increasing_path(matrix: list[list[int]]) -> int—0for an empty matrix.
Example
longest_increasing_path([[9, 9, 4],
[6, 6, 8],
[2, 1, 1]]) -> 4 # 1 -> 2 -> 6 -> 9
longest_increasing_path([[3, 4, 5],
[3, 2, 6],
[2, 2, 1]]) -> 4 # 3 -> 4 -> 5 -> 6
longest_increasing_path([[1]]) -> 1
Constraints
-
0 <= m, n <= 500; values in[0, 2^31 - 1]. - No diagonal moves; equal neighbours don't extend a path.
Clarifying questions
- Strictly increasing, or non-decreasing?
- Four directions only?
- Do you want the length or the path itself?
- How large can the grid be? (Recursion depth can reach
m * n.)
What a strong answer covers
- Strict increase makes the moves a directed acyclic graph, so no visited set is needed and no cycle is possible.
- Memoised DFS:
f(cell) = 1 + max f(neighbour)over larger neighbours, cached per cell.O(m * n)time and space. - The iterative alternative: a topological order (Kahn's algorithm from cells with no smaller neighbour, layer by layer, counting layers), which avoids recursion depth.
- Tests: a single cell, all equal values, a strictly increasing snake.
Follow-ups
- Reconstruct one longest path (store the best next cell).
- Avoid recursion limits on a
500 x 500grid. - Allow diagonal moves, or allow equal values with a visited set (and why that becomes much harder).
Where it's asked
- Meta · AI-enabled coding · Last asked Apr 202660 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
dfs · memoization · matrices
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
