Length of the Longest Increasing Path - Problem

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} and y_i < y_{i+1} for all i where 1 <= i < m
  • (x_i, y_i) is in the given coordinates for all i where 1 <= i <= m

Return the maximum length of an increasing path that contains coordinates[k].

Input & Output

Example 1 — Basic Increasing Path
$ Input: coordinates = [[1,1],[2,3],[4,2],[5,4]], k = 0
Output: 3
💡 Note: Starting from coordinates[0] = (1,1), we can form path (1,1) → (2,3) → (5,4) with length 3
Example 2 — Middle Point
$ Input: coordinates = [[1,1],[2,3],[4,2],[5,4]], k = 1
Output: 2
💡 Note: Starting from coordinates[1] = (2,3), we can form path (2,3) → (5,4) with length 2
Example 3 — Single Point
$ Input: coordinates = [[3,4]], k = 0
Output: 1
💡 Note: Only one point exists, so maximum path length is 1

Constraints

  • 1 ≤ coordinates.length ≤ 103
  • 0 ≤ k < coordinates.length
  • coordinates[i].length == 2
  • -104 ≤ coordinates[i][0], coordinates[i][1] ≤ 104

Visualization

Tap to expand
Length of the Longest Increasing Path INPUT x y [0] (1,1) [1] (2,3) [2] (4,2) [3] (5,4) coordinates array: [1,1] [2,3] [4,2] [5,4] k = 0 (highlighted point) Path must include [0] ALGORITHM STEPS (DP) 1 Sort by x, then y Order: [1,1],[2,3],[4,2],[5,4] 2 DP: paths ending at i dp[i] = max len to point i 3 DP: paths starting at i dp2[i] = max len from point i 4 Combine at k ans = dp[k] + dp2[k] - 1 DP Values: Point: [0] [1] [2] [3] dp_end: 1 2 2 3 dp_start: 3 2 2 1 Increasing Path through k=0: (1,1) --> (2,3) --> (5,4) Length = 1 + 3 - 1 = 3 FINAL RESULT 1,1 2,3 4,2 5,4 Green = in longest path Output: 3 Longest increasing path containing (1,1): (1,1)-->(2,3)-->(5,4) Key Insight: Sort coordinates to enable DP. For each point, compute: (1) longest path ending there, (2) longest path starting there. The answer for point k is dp_end[k] + dp_start[k] - 1 (subtract 1 to avoid counting k twice). An increasing path requires both x and y to strictly increase: x_i < x_{i+1} AND y_i < y_{i+1}. TutorialsPoint - Length of the Longest Increasing Path | DP Approach
Asked in
Google 25 Microsoft 18 Amazon 15
26.3K Views
Medium Frequency
~25 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen