Compute longest increasing path in a matrix
Company: Meta
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Technical Screen
Quick Answer: Compute longest increasing path in a matrix evaluates algorithm design, data structures, correctness, complexity, edge cases, and implementation details in a realistic interview setting. A strong answer states assumptions, handles edge cases, explains trade-offs, and shows how to validate the result clearly.
Constraints
- m == matrix.length
- n == matrix[i].length
- 1 <= m, n <= 200
- 0 <= matrix[i][j] <= 2^31 - 1
Examples
Input: ([[9,9,4],[6,6,8],[2,1,1]],)
Expected Output: 4
Explanation: Longest increasing path is 1 -> 2 -> 6 -> 9 (length 4).
Input: ([[3,4,5],[3,2,6],[2,2,1]],)
Expected Output: 4
Explanation: Longest increasing path is 3 -> 4 -> 5 -> 6 (length 4); diagonal moves are not allowed.
Input: ([[1]],)
Expected Output: 1
Explanation: A single cell is a path of length 1.
Input: ([[1,2,3,4,5,6,7,8,9]],)
Expected Output: 9
Explanation: The entire strictly increasing row forms one path of length 9.
Input: ([[7,7,7],[7,7,7],[7,7,7]],)
Expected Output: 1
Explanation: All values are equal, so no strictly increasing move is possible; the best path is a single cell.
Input: ([],)
Expected Output: 0
Explanation: An empty matrix has no cells, so the longest path length is 0.
Input: ([[1,2],[4,3]],)
Expected Output: 4
Explanation: Path 1 -> 2 -> 3 -> 4 moves right, down, then left, visiting all four cells.
Hints
- Brute-force DFS from every cell recomputes overlapping sub-paths. Notice that the longest increasing path starting at a given cell depends only on that cell — so it can be cached.
- Use memoization: dfs(r, c) = 1 + max(dfs(neighbor)) over the four orthogonal neighbors whose value is strictly greater than matrix[r][c]; default to 1 when no larger neighbor exists.
- Because edges only point from smaller to larger values, the cells form a DAG (no cycles), so memoization never loops. The answer is the maximum dfs value over all cells.
- Follow-up (avoid deep recursion): sort cells by value ascending and relax each cell from its already-processed smaller neighbors, or run a topological/BFS peeling of the DAG — both compute the same DP iteratively with O(1) recursion depth.