Taro Logo

Longest Increasing Path in a Matrix

#73 Most AskedHard
0 views
Topics:
ArraysDynamic ProgrammingGraphsRecursion

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.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 231 - 1

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input matrix is empty (e.g., of size 0x0 or 0xN)?
  2. Can the matrix contain negative numbers, or are all cell values strictly positive?
  3. Since the path must be strictly increasing, how should adjacent cells with equal values be treated?
  4. Are we guaranteed that the matrix dimensions fit entirely in memory, or should I consider memory limits for extremely large grids?
  5. If there are multiple longest increasing paths of the exact same length, does it matter which path's length we return?

Brute Force Solution

Approach

Imagine you are looking at a grid of numbers and need to find the longest path you can take by moving from number to larger number. The brute force strategy involves testing every single possible path starting from every single spot on the board to see how far you can go.

Here's how the algorithm would work step-by-step:

  1. Pick any starting position on the grid as your beginning point.
  2. Look at all the neighboring spots directly above, below, to the left, and to the right of your current position.
  3. If a neighboring spot has a larger number than your current spot, step onto it and continue your journey.
  4. Repeat this process of stepping to larger neighbors until you reach a dead end where no neighboring spots have a larger number.
  5. Count how many steps you took to reach that dead end, and remember that number as the length of that specific path.
  6. Lift your pencil, go back to your very first starting spot, and try a completely different direction if one is available, repeating the whole journey to find another path length.
  7. Once you have exhausted every single path starting from your initial spot, move on to a brand new starting position on the grid and repeat the entire process all over again.
  8. Compare the lengths of every single path you walked across the entire grid, and declare the longest one as your final answer.

Code Implementation

def longestIncreasingPath(matrix):
    if not matrix or not matrix[0]:
        return 0

    row_count = len(matrix)
    col_count = len(matrix[0])

    def explore_paths(current_row, current_col):
        max_path_from_here = 1
        row_offsets = [-1, 1, 0, 0]
        col_offsets = [0, 0, -1, 1]

        # Check all four adjacent directions to find valid strictly increasing neighbors
        for direction_index in range(4):
            next_row = current_row + row_offsets[direction_index]
            next_col = current_col + col_offsets[direction_index]

            if 0 <= next_row < row_count and 0 <= next_col < col_count:
                if matrix[next_row][next_col] > matrix[current_row][current_col]:
                    candidate_path = 1 + explore_paths(next_row, next_col)
                    if candidate_path > max_path_from_here:
                        max_path_from_here = candidate_path

        return max_path_from_here

    overall_max_length = 0

    # Evaluate every single cell in the grid as a starting point for potential paths
    for row_index in range(row_count):
        for col_index in range(col_count):
            path_length = explore_paths(row_index, col_index)
            if path_length > overall_max_length:
                overall_max_length = path_length

    return overall_max_length

Big(O) Analysis

Time Complexity
O(V + E) – The brute force approach repeatedly explores paths from every single cell in the grid, leading to massive overlapping calculations. For an m by n matrix, there are m times n starting positions, and from each position, the recursive exploration can branch out in four directions at each step. In the worst-case scenario without memoization, exploring all valid increasing paths can take exponential time proportional to 4 to the power of the number of cells. When properly optimized with memoization, each cell is computed once and its neighbors are visited a constant number of times, making the time complexity linear with respect to the total number of cells, V, and edges, E, in the grid graph.
Space Complexity
O(mn) – The auxiliary space complexity is driven by two main components: the memoization cache and the recursion call stack. We allocate a memoization table of dimensions matching the input grid containing m rows and n columns to store previously computed path lengths. Additionally, the recursive calls visiting neighboring cells can reach a maximum depth of mn in the worst-case scenario where the entire matrix forms a single increasing path. Combining these structures, the extra memory scales linearly with the total number of elements in the grid, which we denote as N where N equals m times n. Therefore, the overall auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

The optimal strategy involves exploring every possible path of increasing numbers starting from every single spot in the grid. To avoid doing the same exhausting work over and over, we remember the longest path found from any spot we have already visited so we can instantly reuse that information later.

Here's how the algorithm would work step-by-step:

  1. Imagine standing at every single cell in the grid and asking yourself how far you can hike if you only step on numbers that are strictly larger than the one you are currently standing on.
  2. When you look at your four immediate neighbors (up, down, left, right), you only want to move to neighbors that are strictly greater than your current number.
  3. Every time you successfully calculate the longest possible hike starting from a specific cell, write that answer down on a sticky note and place it on that cell.
  4. If you ever wander back to a cell you have already visited during another hike, do not recalculate anything; simply look at the sticky note to instantly know the longest path starting from that cell.
  5. Keep track of the longest hike you found during your entire process.
  6. By never repeating the calculation for any cell more than once, you save an enormous amount of time and efficiently find the absolute longest path possible anywhere in the grid.

Code Implementation

Big(O) Analysis

Time Complexity
O(R * C) – Let R be the number of rows and C be the number of columns in the matrix, meaning the total number of cells is R * C. We visit every single cell in the grid through nested loops to initiate our hikes and explore its four neighbors. Because we store the result of each cell on a sticky note during its first calculation, every cell and its adjacent paths are fully evaluated at most once. This avoids redundant work, meaning the total operations scale linearly with the total number of cells, approximately R * C * 1, which simplifies to O(R * C).
Space Complexity
O(R * C) – The auxiliary space is driven by the memoization table, which is a 2D cache matching the dimensions of the grid to store the longest path for each cell, and the recursion stack which can grow up to the total number of cells in the worst-case scenario. Letting N represent the total number of cells in the matrix (R rows times C columns), the memoization table and recursion stack both require O(N) space. Therefore, the extra memory used scales linearly with the total number of elements in the grid, simplifying to Big O of N.

Edge Cases

Empty or null matrix input
How to Handle:
Return zero immediately as no path can exist in an empty grid.
Matrix with dimensions 1x1
How to Handle:
Return one since a single cell constitutes a valid increasing path of length one.
Matrix with all identical values
How to Handle:
Return one because strictly increasing conditions prevent moving to adjacent cells with equal values.
Matrix with negative numbers and mixed signs
How to Handle:
Standard strict inequality checks work naturally with negative numbers without requiring coordinate shifts.
Graph cycles in the search space
How to Handle:
Memoization combined with strict increasing constraints naturally prevents cycles since you can never revisit a smaller or equal value.
Maximum sized constraints causing deep recursion
How to Handle:
DFS with memoization prevents exponential explosion by computing each cell at most once, running well within stack limits.
Strictly decreasing matrix or V-shaped valleys
How to Handle:
The algorithm explores all four directions from every starting point and caches results to find the globally optimal path.
Extreme integer values at the boundaries of 32-bit limits
How to Handle:
Value comparisons use standard arithmetic which safely handles any valid integer range without overflow risks.
0/257 completed