Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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).
Example 1:
Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].
Example 2:
Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.
Example 3:
Input: matrix = [[1]] Output: 1
Constraints:
m == matrix.lengthn == matrix[i].length1 <= m, n <= 2000 <= matrix[i][j] <= 231 - 1Problem summary: 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).
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Dynamic Programming · Topological Sort
[[9,9,4],[6,6,8],[2,1,1]]
[[3,4,5],[3,2,6],[2,2,1]]
[[1]]
number-of-increasing-paths-in-a-grid)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #329: Longest Increasing Path in a Matrix
class Solution {
private int m;
private int n;
private int[][] matrix;
private int[][] f;
public int longestIncreasingPath(int[][] matrix) {
m = matrix.length;
n = matrix[0].length;
f = new int[m][n];
this.matrix = matrix;
int ans = 0;
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
ans = Math.max(ans, dfs(i, j));
}
}
return ans;
}
private int dfs(int i, int j) {
if (f[i][j] != 0) {
return f[i][j];
}
int[] dirs = {-1, 0, 1, 0, -1};
for (int k = 0; k < 4; ++k) {
int x = i + dirs[k];
int y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) {
f[i][j] = Math.max(f[i][j], dfs(x, y));
}
}
return ++f[i][j];
}
}
// Accepted solution for LeetCode #329: Longest Increasing Path in a Matrix
func longestIncreasingPath(matrix [][]int) (ans int) {
m, n := len(matrix), len(matrix[0])
f := make([][]int, m)
for i := range f {
f[i] = make([]int, n)
}
dirs := [5]int{-1, 0, 1, 0, -1}
var dfs func(i, j int) int
dfs = func(i, j int) int {
if f[i][j] != 0 {
return f[i][j]
}
for k := 0; k < 4; k++ {
x, y := i+dirs[k], j+dirs[k+1]
if 0 <= x && x < m && 0 <= y && y < n && matrix[x][y] > matrix[i][j] {
f[i][j] = max(f[i][j], dfs(x, y))
}
}
f[i][j]++
return f[i][j]
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
ans = max(ans, dfs(i, j))
}
}
return
}
# Accepted solution for LeetCode #329: Longest Increasing Path in a Matrix
class Solution:
def longestIncreasingPath(self, matrix: List[List[int]]) -> int:
@cache
def dfs(i: int, j: int) -> int:
ans = 0
for a, b in pairwise((-1, 0, 1, 0, -1)):
x, y = i + a, j + b
if 0 <= x < m and 0 <= y < n and matrix[x][y] > matrix[i][j]:
ans = max(ans, dfs(x, y))
return ans + 1
m, n = len(matrix), len(matrix[0])
return max(dfs(i, j) for i in range(m) for j in range(n))
// Accepted solution for LeetCode #329: Longest Increasing Path in a Matrix
impl Solution {
pub fn longest_increasing_path(matrix: Vec<Vec<i32>>) -> i32 {
use std::cmp::max;
use std::collections::HashMap;
let mut dp: HashMap::<(usize, usize), i32> = HashMap::new();
fn dfs(
r: usize,
c: usize,
prevVal: i32,
matrix: &[Vec<i32>],
dp: &mut HashMap<(usize, usize), i32>,
) -> i32 {
if r < 0
|| r >= matrix.len()
|| c < 0
|| c >= matrix[0].len()
|| matrix[r][c] <= prevVal
{
return 0;
}
if let Some(&result) = dp.get(&(r, c)) {
return result;
}
let mut res = 1;
res = max(res, 1 + dfs(r + 1, c, matrix[r][c], matrix, dp));
res = max(res, 1 + dfs(r - 1, c, matrix[r][c], matrix, dp));
res = max(res, 1 + dfs(r, c + 1, matrix[r][c], matrix, dp));
res = max(res, 1 + dfs(r, c - 1, matrix[r][c], matrix, dp));
dp.insert((r, c), res);
res
}
for r in 0..matrix.len() {
for c in 0..matrix[0].len() {
dfs(r, c, -1, &matrix, &mut dp);
}
}
*dp.values().max().unwrap_or(&1)
}
}
// Accepted solution for LeetCode #329: Longest Increasing Path in a Matrix
function longestIncreasingPath(matrix: number[][]): number {
const m = matrix.length;
const n = matrix[0].length;
const f: number[][] = Array(m)
.fill(0)
.map(() => Array(n).fill(0));
const dirs = [-1, 0, 1, 0, -1];
const dfs = (i: number, j: number): number => {
if (f[i][j] > 0) {
return f[i][j];
}
for (let k = 0; k < 4; ++k) {
const x = i + dirs[k];
const y = j + dirs[k + 1];
if (x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) {
f[i][j] = Math.max(f[i][j], dfs(x, y));
}
}
return ++f[i][j];
};
let ans = 0;
for (let i = 0; i < m; ++i) {
for (let j = 0; j < n; ++j) {
ans = Math.max(ans, dfs(i, j));
}
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Pure recursion explores every possible choice at each step. With two choices per state (take or skip), the decision tree has 2ⁿ leaves. The recursion stack uses O(n) space. Many subproblems are recomputed exponentially many times.
Each cell in the DP table is computed exactly once from previously solved subproblems. The table dimensions determine both time and space. Look for the state variables — each unique combination of state values is one cell. Often a rolling array can reduce space by one dimension.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.