Overview
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is derived from the array by deleting some or no elements without changing the relative order of the remaining elements.
Constraints
1 <= nums.length <= 2500-10^4 <= nums[i] <= 10^4- Aim for O(n log n) but O(n²) DP is acceptable.
Examples
lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18]); // => 4 (subsequence: [2, 3, 7, 101])
lengthOfLIS([0, 1, 0, 3, 2, 3]); // => 4 (subsequence: [0, 1, 2, 3]) lengthOfLIS([7, 7, 7, 7]); // => 1 (all equal — strictly increasing means length 1)
Solution
Reveal solution
function lengthOfLIS(nums) {
const tails = [];
for (const num of nums) {
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (tails[mid] < num) lo = mid + 1;
else hi = mid;
}
tails[lo] = num;
}
return tails.length;
}The patience sorting approach: maintain an array tails where tails[i] is the smallest tail element for an increasing subsequence of length i+1. Binary search for the insertion point of each element. O(n log n).
Resources
Longest Increasing Subsequence
Overview
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is derived from the array by deleting some or no elements without changing the relative order of the remaining elements.
Constraints
1 <= nums.length <= 2500-10^4 <= nums[i] <= 10^4- Aim for O(n log n) but O(n²) DP is acceptable.
Examples
lengthOfLIS([10, 9, 2, 5, 3, 7, 101, 18]); // => 4 (subsequence: [2, 3, 7, 101])
lengthOfLIS([0, 1, 0, 3, 2, 3]); // => 4 (subsequence: [0, 1, 2, 3]) lengthOfLIS([7, 7, 7, 7]); // => 1 (all equal — strictly increasing means length 1)
Solution
Reveal solution
function lengthOfLIS(nums) {
const tails = [];
for (const num of nums) {
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (tails[mid] < num) lo = mid + 1;
else hi = mid;
}
tails[lo] = num;
}
return tails.length;
}The patience sorting approach: maintain an array tails where tails[i] is the smallest tail element for an increasing subsequence of length i+1. Binary search for the insertion point of each element. O(n log n).