#329
Longest Increasing Path in a Matrix
HardArrayDynamic ProgrammingDepth-First SearchBreadth-First SearchGraph TheoryTopological SortMemoizationMatrixDepth-First SearchMemoizationDynamic Programming
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(m * n) |
| Space | O(1) | O(m * n) |
💡
Intuition
Time O(m * n)Space O(m * n)
The optimal solution uses memoization to store the results of previously computed paths, significantly reducing redundant calculations. This allows us to efficiently find the longest increasing path without re-exploring paths we've already computed.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a memoization table to store the length of the longest increasing path starting from each cell.
- 2Step 2: For each cell, if the result is not already computed, perform a DFS to compute the longest path, storing results in the memo table.
- 3Step 3: Return the maximum value found in the memo table.
solution.py24 lines
1# Full working Python code
2class Solution:
3 def longestIncreasingPath(self, matrix):
4 if not matrix:
5 return 0
6 m, n = len(matrix), len(matrix[0])
7 self.memo = [[-1] * n for _ in range(m)]
8 max_length = 0
9 for i in range(m):
10 for j in range(n):
11 max_length = max(max_length, self.dfs(matrix, i, j))
12 return max_length
13
14 def dfs(self, matrix, x, y):
15 if self.memo[x][y] != -1:
16 return self.memo[x][y]
17 max_length = 1
18 directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
19 for dx, dy in directions:
20 nx, ny = x + dx, y + dy
21 if 0 <= nx < len(matrix) and 0 <= ny < len(matrix[0]) and matrix[nx][ny] > matrix[x][y]:
22 max_length = max(max_length, 1 + self.dfs(matrix, nx, ny))
23 self.memo[x][y] = max_length
24 return max_lengthℹ
Complexity note: The time complexity is O(m * n) because we compute the longest path for each cell exactly once, thanks to memoization. The space complexity is O(m * n) due to the memoization table storing results for each cell.
- 1The longest increasing path can start from any cell.
- 2Memoization is crucial to avoid redundant calculations.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.