Longest Increasing Subsequence
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given an integer array nums, return the length of its longest strictly increasing subsequence.
Understand the problem
- A subsequence keeps some of the elements in their original order, but they don't have to be next to each other:
[3, 7, 101]is a subsequence of[10, 9, 2, 5, 3, 7, 101, 18]. (Compare a subarray, which must be contiguous.) - Strictly increasing means each element is bigger than the one before it. Equal values don't count:
[7, 7]isn't increasing. - You return only the length, not the subsequence itself.
Example 1
Input: nums = [10, 9, 2, 5, 3, 7, 101, 18]
Output: 4For example [2, 3, 7, 101] or [2, 5, 7, 18]. There's no increasing subsequence of length 5.
Example 2
Input: nums = [0, 1, 0, 3, 2, 3]
Output: 4[0, 1, 2, 3].
Example 3
Input: nums = [7, 7, 7, 7]
Output: 1Equal values aren't strictly increasing, so the best is a single 7.
Constraints
1 <= nums.length <= 2500-10^4 <= nums[i] <= 10^4
Note
An O(n²) solution passes. Can you get it down to O(n log n)?
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
Keep, for every possible length, the smallest value an increasing subsequence of that length can end with; each new number either extends the longest one or improves one of those endings, and the number of lengths at the end is the answer.
The naive approach (and why it's slow)
Try every subsequence: each element is in or out, so there are 2^n of them. With 2,500 elements, that's impossible.
Approach 1: O(n²) DP (the easier one to understand)
Ask a smaller question for each position: what's the longest increasing subsequence that ends at nums[i]? Call it lis[i].
A subsequence ending at nums[i] either is just [nums[i]] (length 1), or extends one that ends at an earlier, smaller value nums[j]:
lis[i] = 1 + max(lis[j]) over every j < i with nums[j] < nums[i]
(or 1 if there's no such j)The answer is the largest value in lis. For nums = [10, 9, 2, 5, 3, 7, 101, 18]:
i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
nums[i] | 10 | 9 | 2 | 5 | 3 | 7 | 101 | 18 |
lis[i] | 1 | 1 | 1 | 2 | 2 | 3 | 4 | 4 |
For example lis[5] = 3: 7 can extend the subsequences ending at 2 (length 1), 5 (length 2) or 3 (length 2), so 1 + 2 = 3. The largest value is 4.
Two nested loops: O(n²), about 6 million steps for 2,500 elements. That passes.
Approach 2: O(n log n) with "tails" (used in the reference solution)
The key insight: among all increasing subsequences of the same length, the one ending with the smallest value is the most useful, because more future numbers can extend it.
So keep an array tails, where tails[k] = the smallest last value of any increasing subsequence of length k + 1 found so far. tails is always sorted (a longer subsequence has to end with a bigger value), so you can binary search it.
For each new number x, find the first tail that is >= x:
- There's none (
xis bigger than every tail):xextends the longest subsequence. Append it. - Found at position
k:xis a smaller ending for lengthk + 1. Replacetails[k]withx.
Step by step
nums = [10, 9, 2, 5, 3, 7, 101, 18]:
x | First tail >= x | Action | tails after |
|---|---|---|---|
| 10 | none | append | [10] |
| 9 | 10 (position 0) | replace | [9] |
| 2 | 9 (position 0) | replace | [2] |
| 5 | none | append | [2, 5] |
| 3 | 5 (position 1) | replace | [2, 3] |
| 7 | none | append | [2, 3, 7] |
| 101 | none | append | [2, 3, 7, 101] |
| 18 | 101 (position 3) | replace | [2, 3, 7, 18] |
Answer: tails.length = 4.
Careful: tails is not necessarily a real subsequence (it can mix values from different ones). Only its length is guaranteed to be the answer.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Approach 1: O(n²) time, O(n) memory.
- Approach 2: O(n log n) time (one binary search per element), O(n) memory.
Common mistakes
- Allowing equal values. "Strictly increasing" means
<, not<=. That's why the binary search looks for the first tail>= x(so an equal value replaces, never appends). - Mixing up subsequence and subarray. The elements don't need to be next to each other.
- Returning
lis[n - 1]in approach 1. The longest subsequence doesn't have to end at the last element; take the maximum over alli. - Treating
tailsas the actual answer subsequence.
Going deeper
- The
tailstrick is sometimes called patience sorting, after a card game where you deal cards into piles. - Longest Common Subsequence (in 2-D DP) is a different problem with a similar name: it compares two sequences.
Reference solution
/**
* @param {number[]} nums
* @return {number}
*/
export default function lengthOfLis(nums) {
// tails[k] = the smallest last value of any increasing subsequence of length k + 1.
// It's always sorted, so we can binary search it.
const tails = []
for (const x of nums) {
// Binary search for the first tail >= x (tails.length if there's none).
let lo = 0
let hi = tails.length
while (lo < hi) {
const mid = (lo + hi) >> 1
if (tails[mid] < x) lo = mid + 1
else hi = mid
}
// lo === tails.length: x extends the longest subsequence (this appends).
// Otherwise: x is a smaller ending for length lo + 1, so it replaces that tail.
tails[lo] = x
}
return tails.length // tails isn't a real subsequence, but its length is the answer
}export default function lengthOfLis(nums: number[]): number {
// tails[k] = the smallest last value of any increasing subsequence of length k + 1.
// It's always sorted, so we can binary search it.
const tails: number[] = []
for (const x of nums) {
// Binary search for the first tail >= x (tails.length if there's none).
let lo = 0
let hi = tails.length
while (lo < hi) {
const mid = (lo + hi) >> 1
if (tails[mid] < x) lo = mid + 1
else hi = mid
}
// lo === tails.length: x extends the longest subsequence (this appends).
// Otherwise: x is a smaller ending for length lo + 1, so it replaces that tail.
tails[lo] = x
}
return tails.length // tails isn't a real subsequence, but its length is the answer
}from bisect import bisect_left
def length_of_lis(nums: list[int]) -> int:
# tails[k] = the smallest last value of any increasing subsequence of length k + 1.
# It's always sorted, so we can binary search it.
tails = []
for x in nums:
k = bisect_left(tails, x) # position of the first tail >= x
if k == len(tails):
tails.append(x) # x extends the longest subsequence
else:
tails[k] = x # a smaller ending for length k + 1
return len(tails) # tails isn't a real subsequence, but its length is the answer