Tutorialspoint
Problem
Solution
Submissions

Longest Increasing Path

Certification: Advanced Level Accuracy: 100% Submissions: 1 Points: 15

Given an m x n integer matrix, find the length of the longest increasing path in the matrix. From each cell, you can move to any adjacent cell (up, down, left, or right) if the next cell's value is strictly greater than the current cell's value.

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]. The path starts at position (2, 1) with value 1, then moves to (2, 0) with value 2, then to (1, 0) with value 6, and finally to (0, 0) with value 9. The length of this path is 4.
Example 2
  • Input: matrix = [[3, 4, 5], [3, 2, 6], [2, 2, 1]]
  • Output: 4
  • Explanation: The longest increasing path is [1, 2, 3, 4, 5]. The path starts at position (2, 2) with value 1, then moves to (2, 1) with value 2, then to (1, 1) with value 2 (same value, not increasing), then to (0, 0) with value 3, then to (0, 1) with value 4, and finally to (0, 2) with value 5. The length of the increasing path is 4.
Constraints
  • m == matrix.length
  • n == matrix[i].length
  • 1 <= m, n <= 200
  • 0 <= matrix[i][j] <= 2^31 - 1
  • Time Complexity: O(m * n), where m and n are the dimensions of the matrix
  • Space Complexity: O(m * n)
MatrixCognizantAirbnb
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Depth-First Search (DFS) with memoization to avoid redundant calculations
  • For each cell, explore all four directions (up, down, left, right) if the next cell has a larger value
  • Use a memo array to store the longest path starting from each cell
  • The answer will be the maximum value in the memo array
  • Using memoization reduces the time complexity from exponential to linear

Steps to solve by this approach:

 Step 1: Define a 2D array to represent the four possible directions: up, down, left, and right.

 Step 2: Create a memoization array to store the longest path length starting from each cell.
 Step 3: For each cell in the matrix, perform a DFS to find the longest increasing path starting from that cell.
 Step 4: In the DFS function, first check if the result is already memoized. If yes, return it directly.
 Step 5: Otherwise, explore all four directions. If the next cell has a greater value, recursively calculate the longest path from that cell.
 Step 6: Update the maximum path length and memoize the result for the current cell.
 Step 7: Return the overall maximum path length found across all cells.

Submitted Code :