Longest Increasing Subsequence
Longest Increasing Subsequence is LeetCode 300 (Medium). Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence keeps the original order but may skip elements, so the chosen numbers do not have to be next to each other. Equal neighbours do not count as increasing.
The follow-up asks for O(n log n) time.
- 1 <= nums.length <= 2500
- -10⁴ <= nums[i] <= 10⁴
Intuition
Many increasing subsequences of the same length can exist, but only one of them matters: the one that ends in the smallest number. Any later value that extends a chain ending in 9 also extends a chain ending in 2, so the chain ending in 9 can be forgotten.
So keep tails, where tails[k] is the smallest possible last number of an increasing subsequence of length k + 1. This list is always sorted. Each new number either goes past the end (a longer chain exists) or replaces the first entry that is not smaller than it (an equally long chain now ends lower). Finding that spot is a binary search, so each number costs O(log n).
Approach
Two ways to find the length
Keep the smallest ending for each length and binary search it.
- Fast: answers the follow-up.
- Short: five lines in the loop.
Gives the length; printing the numbers needs an extra link per element.
dp[i] is the longest increasing subsequence ending at index i.
- Natural first idea: easy to derive in an interview.
- Adapts easily: counting or weighting chains changes one line.
Pick it when n is small or the variant needs more than a length.
Both work within the limits here (n ≤ 2500). The tails list is the one traced below; the quadratic DP follows the demo.
Start with an empty tails list
tails will hold one entry per possible length. It starts empty because no subsequence has been seen yet.
Binary search for each number's place
For each x, find k, the first index with tails[k] >= x (bisect_left). Every entry before k is smaller than x, so x can extend a chain of length k into one of length k + 1.
Append or replace
- If
k == len(tails), every tail is smaller thanx: append it, the longest chain just grew. - Otherwise set
tails[k] = x. The length stays the same, but a chain of that length now ends in a smaller number, which can only help later values.
Why the list stays sorted
x lands just after the last entry smaller than it and replaces an entry at least as big. So it is bigger than the entry before it and not bigger than the one it replaced, which keeps the list increasing and the binary search valid.
Return the length
The answer is len(tails): one entry exists for every length that some increasing subsequence reaches.
Code in Python, C++ and Java
DP over earlier elements
dp[i] starts at 1 (the element alone). For every earlier j with nums[j] < nums[i], the chain ending at j can be extended by nums[i], so dp[i] takes the best dp[j] + 1. The answer is the largest value anywhere in dp, because the longest chain can end at any index.
Common pitfalls
Using bisect_right
k = bisect_right(tails, x)
k = bisect_left(tails, x)
bisect_right puts an equal value after its twin, so [7, 7, 7] grows to 3. Equal numbers are not strictly increasing; bisect_left makes the second 7 replace the first and the answer stays 1.
Returning tails as the subsequence
return tails
return len(tails)
On [3, 4, 1] the list ends as [1, 4], but 1 comes after 4 in the input, so that is not a subsequence at all. Only the length is guaranteed.
Returning the last DP value in the O(n²) version
return dp[-1]
return max(dp)
dp[i] is the best chain ending at i. On [1, 2, 0] the last value is 1, but the answer is 2 from [1, 2].
Complexity
Longest Increasing Subsequence FAQ
How do I get the actual numbers, not just the length?
Store, next to each number, the index of the number it was placed after: the current last entry of the length one shorter. When you finish, start from the last entry of the longest length and follow those links backwards, then reverse. The demo above does exactly this. In the O(n²) DP the same idea works with a parent[i] = j array saved whenever dp[i] improves.
Why is this called patience sorting?
It mirrors the card game: deal each card onto the leftmost pile whose top is not smaller, or start a new pile. The tops of the piles are exactly the tails list, and the number of piles is the answer. The idea was studied as a way to sort a deck, which is where the name comes from.
How do I find the longest non-decreasing subsequence instead?
Swap bisect_left for bisect_right. Then a value equal to a tail goes after it and can extend the chain, so [7, 7, 7] gives 3.