KatInterview

329. Longest Increasing Path in a Matrix

HardSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the length of the longest strictly increasing path in a given m x n integer matrix. We can move from a cell to its four adjacent neighbors (up, down, left, right). This problem can be modeled as finding the longest path in a Directed Acyclic Graph (DAG). Each cell in the matrix is a node in the graph. A directed edge exists from cell A to cell B if B is adjacent to A and the value of B is strictly greater than the value of A. Since we can only move to cells with larger values, there can be no cycles, hence it's a DAG.

Solution

Longest Increasing Path in a Matrix in Python

class Solution:
    def longestIncreasingPath(self, matrix: list[list[int]]) -> int:
        if not matrix or not matrix[0]:
            return 0

        m, n = len(matrix), len(matrix[0])
        # dp[(r, c)] stores the length of the longest increasing path starting from cell (r, c)
        dp = {}

        def dfs(r: int, c: int) -> int:
            # If the result for this cell is already computed, return it.
            if (r, c) in dp:
                return dp[(r, c)]
            
            # The path length is at least 1 (the cell itself).
            max_path = 1

            # Explore 4 directions
            for dr, dc in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
                nr, nc = r + dr, c + dc

                # Check boundaries and increasing path condition
                if 0 <= nr < m and 0 <= nc < n and matrix[nr][nc] > matrix[r][c]:
                    # The path length is 1 (current cell) + longest path from the neighbor
                    max_path = max(max_path, 1 + dfs(nr, nc))
            
            # Memoize the result and return it.
            dp[(r, c)] = max_path
            return max_path

        longest_path = 0
        # Iterate through each cell as a potential starting point
        for r in range(m):
            for c in range(n):
                longest_path = max(longest_path, dfs(r, c))

        return longest_path

Longest Increasing Path in a Matrix in Java

class Solution {
    private int m, n;
    private int[][] matrix;
    private int[][] dp;
    private int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public int longestIncreasingPath(int[][] matrix) {
        if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
            return 0;
        }
        
        this.m = matrix.length;
        this.n = matrix[0].length;
        this.matrix = matrix;
        // dp[i][j] stores the length of the longest increasing path starting from cell (i, j)
        this.dp = new int[m][n];
        
        int longestPath = 0;
        // Iterate through each cell as a potential starting point
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                longestPath = Math.max(longestPath, dfs(i, j));
            }
        }
        
        return longestPath;
    }

    // DFS with memoization
    private int dfs(int r, int c) {
        // If the result for this cell is already computed, return it.
        if (dp[r][c] != 0) {
            return dp[r][c];
        }

        // The path length is at least 1 (the cell itself).
        int maxPath = 1;

        // Explore 4 directions
        for (int[] dir : dirs) {
            int nr = r + dir[0];
            int nc = c + dir[1];

            // Check boundaries and increasing path condition
            if (nr >= 0 && nr < m && nc >= 0 && nc < n && matrix[nr][nc] > matrix[r][c]) {
                // The path length is 1 (current cell) + longest path from the neighbor
                maxPath = Math.max(maxPath, 1 + dfs(nr, nc));
            }
        }

        // Memoize the result and return it.
        dp[r][c] = maxPath;
        return maxPath;
    }
}

Longest Increasing Path in a Matrix in C++

class Solution {
private:
    int m, n;
    vector<vector<int>> dp;
    int dirs[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    // DFS with memoization to find the longest increasing path starting from (r, c)
    int dfs(const vector<vector<int>>& matrix, int r, int c) {
        // If the result for this cell is already computed, return it.
        if (dp[r][c] != 0) {
            return dp[r][c];
        }

        // The path length is at least 1 (the cell itself).
        int maxPath = 1;

        // Explore 4 directions
        for (auto& dir : dirs) {
            int nr = r + dir[0];
            int nc = c + dir[1];

            // Check boundaries and increasing path condition
            if (nr >= 0 && nr < m && nc >= 0 && nc < n && matrix[nr][nc] > matrix[r][c]) {
                // The path length is 1 (current cell) + longest path from the neighbor
                maxPath = max(maxPath, 1 + dfs(matrix, nr, nc));
            }
        }

        // Memoize the result and return it.
        return dp[r][c] = maxPath;
    }

public:
    int longestIncreasingPath(vector<vector<int>>& matrix) {
        if (matrix.empty() || matrix[0].empty()) {
            return 0;
        }

        m = matrix.size();
        n = matrix[0].size();
        // Initialize DP table with 0s
        dp.assign(m, vector<int>(n, 0));

        int longestPath = 0;
        // Iterate through each cell as a potential starting point
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                longestPath = max(longestPath, dfs(matrix, i, j));
            }
        }

        return longestPath;
    }
};

Longest Increasing Path in a Matrix in TypeScript

function longestIncreasingPath(matrix: number[][]): number {
    if (!matrix || matrix.length === 0 || matrix[0].length === 0) {
        return 0;
    }

    const m = matrix.length;
    const n = matrix[0].length;
    // dp[i][j] stores the length of the longest increasing path starting from cell (i, j)
    const dp = Array(m).fill(0).map(() => Array(n).fill(0));
    const dirs = [[0, 1], [0, -1], [1, 0], [-1, 0]];

    // DFS with memoization
    const dfs = (r: number, c: number): number => {
        // If the result for this cell is already computed, return it.
        if (dp[r][c] !== 0) {
            return dp[r][c];
        }

        // The path length is at least 1 (the cell itself).
        let maxPath = 1;

        // Explore 4 directions
        for (const dir of dirs) {
            const nr = r + dir[0];
            const nc = c + dir[1];

            // Check boundaries and increasing path condition
            if (nr >= 0 && nr < m && nc >= 0 && nc < n && matrix[nr][nc] > matrix[r][c]) {
                // The path length is 1 (current cell) + longest path from the neighbor
                maxPath = Math.max(maxPath, 1 + dfs(nr, nc));
            }
        }

        // Memoize the result and return it.
        dp[r][c] = maxPath;
        return maxPath;
    };

    let longestPath = 0;
    // Iterate through each cell as a potential starting point
    for (let i = 0; i < m; i++) {
        for (let j = 0; j < n; j++) {
            longestPath = Math.max(longestPath, dfs(i, j));
        }
    }

    return longestPath;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.