#3288

Length of the Longest Increasing Path

Hard
ArrayBinary SearchSortingDynamic ProgrammingSortingGreedy Algorithms
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal solution leverages sorting and dynamic programming to efficiently count the longest increasing path. By sorting the coordinates based on x and y values, we can ensure we only consider valid increasing paths.

⚙️

Algorithm

3 steps
  1. 1Step 1: Filter out coordinates that are not strictly less than coordinates[k].
  2. 2Step 2: Sort the remaining coordinates by x, and by y in descending order for ties.
  3. 3Step 3: Use dynamic programming to find the longest increasing path length.
solution.py18 lines
1# Full working Python code
2from typing import List
3
4def longestIncreasingPath(coordinates: List[List[int]], k: int) -> int:
5    target = coordinates[k]
6    filtered = [p for p in coordinates if p[0] < target[0] and p[1] < target[1]]
7    filtered.sort(key=lambda x: (x[0], -x[1]))
8    dp = [1] * len(filtered)
9    max_length = 0
10    for i in range(len(filtered)):
11        for j in range(i):
12            if filtered[j][1] < filtered[i][1]:
13                dp[i] = max(dp[i], dp[j] + 1)
14        max_length = max(max_length, dp[i])
15    return max_length + 1  # +1 for the target point
16
17# Example usage
18print(longestIncreasingPath([[3,1],[2,2],[4,1],[0,0],[5,3]], 1))

Complexity note: The time complexity is O(n log n) due to the sorting step, and O(n) for the dynamic programming part, making it efficient for larger inputs.

  • 1Filtering coordinates based on the target is crucial to reduce unnecessary checks.
  • 2Sorting helps in efficiently finding increasing paths by ensuring we only consider valid pairs.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.