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.
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.