You are given an integer array nums and an integer k. Your task is to find the longest subsequence that satisfies two important conditions:

  1. The subsequence is strictly increasing
  2. The difference between any two adjacent elements in the subsequence is at most k

A subsequence is derived from the original array by deleting some or no elements without changing the order of the remaining elements. For example, from array [4,2,1,4,3,4,5,8,15], a valid subsequence could be [2,4,5,8].

Return the length of the longest subsequence that meets both requirements.

Example: If nums = [4,2,1,4,3,4,5,8,15] and k = 3, one possible longest increasing subsequence with difference ≤ 3 could be [1,3,4,5,8] with length 5.

Input & Output

example_1.py — Basic Case
$ Input: nums = [4,2,1,4,3,4,5,8,15], k = 3
› Output: 5
šŸ’” Note: One possible longest increasing subsequence is [1,3,4,5,8] with length 5. Each adjacent pair has difference ≤ 3: 3-1=2, 4-3=1, 5-4=1, 8-5=3.
example_2.py — Small Difference
$ Input: nums = [7,4,5,1,8,12,4,7], k = 5
› Output: 4
šŸ’” Note: One possible longest increasing subsequence is [4,5,7,12] with length 4. Differences: 5-4=1, 7-5=2, 12-7=5 (all ≤ 5).
example_3.py — Edge Case
$ Input: nums = [1,5], k = 1
› Output: 1
šŸ’” Note: Cannot form increasing subsequence of length > 1 because 5-1=4 > k=1. Maximum length is 1.

Visualization

Tap to expand
Constrained LIS: Step by Step421431→4: diff=3≤kValid: 4-3=1≤klen=1len=1len=1len=2len=2Current subsequence: [1, 3] with length 2
Understanding the Visualization
1
Scan Array
Process each element from left to right
2
Find Valid Range
For current element x, find all previous elements in range [x-k, x-1]
3
Get Maximum
Query the maximum subsequence length ending in the valid range
4
Update Tree
Update data structure with new maximum length at current position
Key Takeaway
šŸŽÆ Key Insight: Use segment tree with coordinate compression to efficiently query the maximum subsequence length in any value range, reducing time complexity from O(n²) to O(n log n).

Time & Space Complexity

Time Complexity
ā±ļø
O(n log n)

Coordinate compression O(n log n) + n operations on segment tree O(log n) each

n
2n
⚔ Linearithmic
Space Complexity
O(n)

Segment tree and coordinate compression arrays

n
2n
⚔ Linearithmic Space

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i], k ≤ 105
  • The array can contain duplicate values
  • Subsequence must be strictly increasing (no equal elements)
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
28.5K Views
Medium Frequency
~35 min Avg. Time
892 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