LIS in O(n log n) with binary search
1 Keep the cards that go up
A dealer turns cards face up, one at a time: 4, 9, 6, 2, 7, 3, 8, 5. We may keep any of them, in the order they came, but each kept card must be bigger than the one before it. The most we can keep is four: 4, 6, 7 and 8.
In code, the cards are an array nums, and the kept cards are a subsequence, as in the pick-or-skip lesson. The longest one that goes up is the longest increasing subsequence, or LIS. Increasing means strictly, so two equal values cannot both be kept. LeetCode asks for its length, in lengthOfLIS.
Trying every subsequence takes about 2ⁿ steps. This lesson first builds an O(n²) DP. Then it replaces the DP with one sorted array and a binary search per card.
2 The O(n²) DP: the best run ending here
The DP lessons start with a state. Here it is dp[i]: the length of the longest increasing subsequence that ends at index i. Ending at i fixes the last card. So any earlier card that is smaller can come just before it.
When no earlier card is smaller, dp[i] is 1: the card on its own. In each step below, orange marks card i, blue marks the smaller cards before it, and the arrows show the dp values that dp[i] reads:
The full array is [1, 2, 2, 1, 3, 2, 4, 3]. The answer is its largest value, 4. It is not dp[7], because the best run does not have to end on the last card.
for i from 0 to n - 1
dp[i] = 1
for j from 0 to i - 1
if nums[j] < nums[i]
dp[i] = max(dp[i], dp[j] + 1)
answer = the largest dp[i]
The inner loop looks at every earlier card, so the work is about n²/2 steps. At n = 10⁵ that is around 5 × 10⁹ steps. At about 10⁸ steps a second, it is far past the time limit, so it gets Time Limit Exceeded (TLE).
3 Keep only the smallest tail
The DP remembers a run for every card, and most of them never matter. After 4, 9 and 6, there are two runs of length 2: 4, 9 and 4, 6. Any card that can follow 9 can also follow 6. And 4, 6 can also take a 7 or an 8. So a run with a smaller tail is never worse, and we can forget 4, 9.
So for each length, we keep only the smallest card that ends a run of that length. These cards live in an array tails: tails[k] is the smallest tail of an increasing subsequence of length k + 1.
The card game patience builds the same array. We deal the cards into piles. Each card goes on the leftmost pile whose top is at least as big as the card. If no pile has such a top, the card starts a new pile on the right:
The top of pile k is the smallest card so far that ends a run of length k + 1. So the tops, 2, 3, 5 and 8, are exactly tails, and four piles mean an LIS of length 4.
4 Tracing tails
The tops go up from left to right, so tails is sorted. The leftmost pile whose top is at least x is then the first tail ≥ x: the lower bound from the binary search lesson. For each card x, we find that position, pos:
- Some tail is ≥ x. x replaces
tails[pos]. That length now ends lower. - Every tail is smaller. x goes on the end, and the LIS grows by one.
Here is the whole deal. Orange marks the card that arrives, and blue marks the slot of tails it writes:
The same run as a table:
| x | tails before | pos | move | tails after |
|---|---|---|---|---|
| 4 | [ ] | 0 | append | [4] |
| 9 | [4] | 1 | append | [4, 9] |
| 6 | [4, 9] | 1 | replace 9 | [4, 6] |
| 2 | [4, 6] | 0 | replace 4 | [2, 6] |
| 7 | [2, 6] | 2 | append | [2, 6, 7] |
| 3 | [2, 6, 7] | 1 | replace 6 | [2, 3, 7] |
| 8 | [2, 3, 7] | 3 | append | [2, 3, 7, 8] |
| 5 | [2, 3, 7, 8] | 2 | replace 7 | [2, 3, 5, 8] |
tails grew on four cards, and those four appends are the answer. The other four cards only lowered a tail, so that later cards could follow them.
tails ends as [2, 3, 5, 8], and that is not a subsequence of nums:
Each slot is the best tail for its own length, and the slots come from different runs. The 5 says a run of length 3 can end in 5 (2, 3, 5). It does not say that 8 follows it. Only the length of tails is the answer. The real LIS is 4, 6, 7, 8.
5 Why replacing is safe
The method rests on two facts.
tails is sorted. The run ending in tails[k + 1] has a card just before its last one, and that card ends a run of length k + 1. So that card is at least tails[k], and the last card is bigger still.
A card x changes only slot pos. The tails before pos are smaller than x, so x can follow the run in slot pos - 1. That makes a run of length pos + 1 ending in x. No longer run can end in x. It would need a run of length pos + 1 ending below x, but the smallest such ending, tails[pos], is at least x. For the shorter lengths, x is bigger than the tail already there.
So writing x into slot pos keeps every slot the smallest tail for its length. When pos is past the end, x ends a run longer than any before, and tails grows.
6 The code and its cost
The loop is the trace table: one lower bound per card, then a replace or an append.
C++
lower_bound does the search. It returns an iterator to the first tail ≥ x, and subtracting tails.begin() turns it into pos.
A fixed array and a size. tails has room for n values, and size says how many are in use. Writing at pos == size is an append, so one line covers both moves. Java has no lower bound built in, so the helper is the loop from the binary search lesson.
bisect_left is the lower bound. It returns the first index whose value is ≥ x, or len(tails) when there is none.
No built-in binary search. The helper is the lower bound loop from the binary search lesson.
sort.SearchInts(tails, x) returns the first index whose value is ≥ x, or len(tails) when there is none.
partition_point(|&t| t < x) returns the first index where t < x turns false. That is the first tail ≥ x.
A helper for the lower bound. List<int>.BinarySearch returns a flipped insert position when x is missing, which is easy to misread. The helper is the loop from the binary search lesson.
Every tab returns 4 on our cards, 1 on [7, 7, 7, 7], and 100000 on 10⁵ values in increasing order.
Each card does one binary search over tails, which never holds more than n values. That is O(log n) per card, so the whole run takes O(n log n) time. At n = 10⁵, it is about 2 × 10⁶ steps, against 5 × 10⁹ for the DP:
tails holds at most n values, so the extra space is O(n).
7 Rebuilding the LIS, and other versions
Printing a real LIS. Beside each slot, we store the index of its card in tailIndex. When card i lands in slot pos, its parent is the card then in slot pos - 1: parent[i] = tailIndex[pos - 1]. At the end, we follow the parents back from the card in the last slot:
Read backwards, that is 4, 6, 7, 8. A parent is fixed when its card lands, so later replacements cannot break the chain.
Non-decreasing runs. When equal values may both be kept, we search for the first tail greater than x, the upper bound. That is the only change. On [3, 5, 5, 6], the second 5 then goes on the end instead of replacing the first:
| x | tails, lower bound | tails, upper bound |
|---|---|---|
| 3 | [3] | [3] |
| 5 | [3, 5] | [3, 5] |
| 5 | [3, 5] | [3, 5, 5] |
| 6 | [3, 5, 6] | [3, 5, 5, 6] |
Other problems build on the same two methods:
- Number of LIS. In the O(n²) DP, keep
count[i]besidedp[i]: how many best runs end at i. A longer run through j copiescount[j], and a tie adds it. - Russian doll envelopes. Sort by width going up, and by height going down on a tie, then take the LIS of the heights. Envelopes of the same width cannot nest, and with their heights going down, a strictly increasing run never takes two of them.
- Longest bitonic subsequence. The run goes up, then down. Take the LIS ending at each i from the left, and the one starting at i from the right. The answer is the largest left[i] + right[i] − 1.
- A test other than "smaller". Largest Divisible Subset and Longest String Chain are the O(n²) DP with their own test, once the items are in a good order.
8 Mistakes, and when to use it
- Upper bound for a strict LIS. On
[7, 7, 7, 7], every 7 goes on the end, and the answer comes out as 4 instead of 1. - Printing
tailsas the LIS. On our cards, it prints 2, 3, 5, 8, but the 8 comes before the 5 innums. - Returning
dp[n - 1]from the O(n²) DP. On our cards, it returns 3 instead of 4. The best run ends at the 8, not at the last card. - The wrong tie order for envelopes. Take the envelopes [3, 4], [3, 5] and [5, 6]. With heights going up on the tie, the heights read 4, 5, 6, and the answer comes out as 3. The two envelopes of width 3 cannot nest, so the answer is 2.
The sign is an answer that is a subsequence that must keep going up. Then the question picks the method:
- Only the length, with n up to 10⁵. Use
tailsand a lower bound. - A count, or a test other than "smaller". Use the O(n²) DP. It is fast enough up to about n = 10⁴.
- Pairs such as envelopes. Sort by one value, run the LIS on the other, and pick the tie order with care.
The next topic moves DP onto a grid, where the state is a cell instead of one index.
Practice it
Finished this lesson?
Mark it read and it is ticked on the roadmap and in the list.