Length of the Longest Increasing Path Problem
Description
LeetCode Problem 3288.
You are given a 2D array of integers coordinates of length n and an integer k, where 0 <= k < n.
coordinates[i] = [x_i, y_i] indicates the point (x_i, y_i) in a 2D plane.
An increasing path of length m is defined as a list of points (x_1, y_1), (x_2, y_2), (x_3, y_3), ..., (x_m, y_m) such that:
x_i < x_(i + 1)andy_i < y_(i + 1)for alliwhere1 <= i < m.(x_i, y_i)is in the given coordinates for alliwhere1 <= i <= m.
Return the maximum length of an increasing path that contains coordinates[k].
Example 1:
Input: coordinates = [[3,1],[2,2],[4,1],[0,0],[5,3]], k = 1
Output: 3
Explanation:
(0, 0), (2, 2), (5, 3) is the longest increasing path that contains (2, 2).
Example 2:
Input: coordinates = [[2,1],[7,0],[5,6]], k = 2
Output: 2
Explanation:
(2, 1), (5, 6) is the longest increasing path that contains (5, 6).
Constraints:
1 <= n == coordinates.length <= 10^5coordinates[i].length == 20 <= coordinates[i][0], coordinates[i][1] <= 10^9- All elements in
coordinatesare distinct. 0 <= k <= n - 1
Solution
Approach: Two Longest Increasing Subsequences
A path through coordinates[k] splits into two parts: the points before it, which must be strictly smaller in both x and y, and the points after it, which must be strictly larger in both. The two parts are independent, so the answer is left + right + 1, where left and right are the longest increasing paths among the points in each part.
Each part is a classic longest increasing subsequence problem. Sort its points by x ascending and, for equal x, by y descending (so two points with the same x can never both be used). Then the longest path is the length of the longest strictly increasing subsequence of the y values, which binary search over a "tails" array finds in O(n log n).
Complexity:
- Time complexity:
O(n log n) - Space complexity:
O(n)
from bisect import bisect_left
class Solution:
def maxPathLength(self, coordinates: List[List[int]], k: int) -> int:
kx, ky = coordinates[k]
def lis(points: List[List[int]]) -> int:
points.sort(key=lambda p: (p[0], -p[1]))
d = []
for _, y in points:
i = bisect_left(d, y)
if i == len(d):
d.append(y)
else:
d[i] = y
return len(d)
left = lis([p for p in coordinates if p[0] < kx and p[1] < ky])
right = lis([p for p in coordinates if p[0] > kx and p[1] > ky])
return left + right + 1