Longest increasing subsequence: from O(n²) to O(n log n)
Question
A shop records an item's price each week: [4, 9, 5, 2, 7, 3, 8, 1]. Find the length of the longest strictly increasing subsequence. A subsequence keeps the original order but may skip items. Here the answer is 4: 4, 5, 7, 8. First describe an O(n²) solution. Then write one that runs in O(n log n).
lis_length([4, 9, 5, 2, 7, 3, 8, 1]) # 4 lis_length([4, 4, 4]) # 1, equal is not increasing lis_length([]) # 0
def lis_length(nums): ...
Show hints (3)
- "A SMALLER QUESTION"
For each index
i, what is the longest increasing subsequence that ends exactly atnums[i]? It extends one that ends earlier, at a smaller value. - "WHAT TO REMEMBER"
For the fast version, keep one number per length: the smallest value that an increasing subsequence of that length can end with. A smaller end leaves more room for later numbers.
- "WHERE IT GOES"
That list stays sorted. For each
x,bisect_leftfinds the first value that is>= x. Replace that value withx, or appendxif it is bigger than all of them.
Show checked explanation
In O(n²), find for each item the longest increasing subsequence that ends at it. It extends the best one that ends at an earlier, smaller item. In O(n log n), keep tails: tails[k] is the smallest last value of an increasing subsequence of length k + 1. Place each number with a binary search. The answer is len(tails).
from bisect import bisect_left def lis_length(nums): # tails[k]: smallest end of an increasing subsequence of length k + 1 tails = [] for x in nums: i = bisect_left(tails, x) if i == len(tails): tails.append(x) else: tails[i] = x return len(tails) print(lis_length([4, 9, 5, 2, 7, 3, 8, 1])) print(lis_length([4, 4, 4])) print(lis_length([]))
4 1 0
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Start with the O(n²) version. best[i] is the length of the longest increasing subsequence that ends at nums[i]. It is 1 more than the largest best[j] with j < i and nums[j] < nums[i], or 1 if there is no such j:
def lis_quadratic(nums): best = [1] * len(nums) for i in range(len(nums)): for j in range(i): if nums[j] < nums[i]: best[i] = max(best[i], best[j] + 1) return max(best, default=0)
For the prices, best is [1, 2, 2, 1, 3, 2, 4, 1]. The answer is the largest value, 4, which ends at the price 8.
The fast version keeps tails. For each price, bisect_left finds the first tail that is greater than or equal to it:
| price | step | tails |
|---|---|---|
| 4 | append | [4] |
| 9 | append | [4, 9] |
| 5 | replace 9 | [4, 5] |
| 2 | replace 4 | [2, 5] |
| 7 | append | [2, 5, 7] |
| 3 | replace 5 | [2, 3, 7] |
| 8 | append | [2, 3, 7, 8] |
| 1 | replace 2 | [1, 3, 7, 8] |
Why replace? After 4, 9 and 5, both 4, 9 and 4, 5 have length 2. Ending at 5 is better, because more later prices can extend it. A replace never changes the length of tails. The new value is bigger than the tail before it and no bigger than the one it replaces, so tails stays sorted. Its length always equals the longest length found so far. Each price costs one binary search, so the total is O(n log n).
The final tails is [1, 3, 7, 8]. That is not a real subsequence, because 1 is the last price. Only its length is the answer.
Common mistakes
- Returning
tailsas the subsequence. For the prices it is[1, 3, 7, 8], but 1 comes after 8 in the input. - Using
bisect_rightfor a strictly increasing subsequence. Equal values then extend the subsequence, so[4, 4, 4]gives 3 instead of 1. - Returning
best[-1]instead ofmax(best)in the O(n²) version. The best subsequence need not end at the last item. For the prices,best[-1]is 1, but the answer is 4. - Taking each price that beats the last one you took. That greedy rule takes 4, then 9, and gets stuck at length 2.
Follow-up questions
- "Return one longest subsequence, not only its length." Store indexes in
tailsinstead of values, and search withbisect_left(tails, x, key=nums.__getitem__). When you place an item, also save the index stored in the slot to its left: that is the item before it. At the end, start from the last slot and follow these links back. For the prices you get4, 5, 7, 8. It is still O(n log n). - "What if equal values are allowed, so
4, 4, 4has length 3?" That is the longest non-decreasing subsequence. Usebisect_right, so an equal value goes after the tails that match it and can extend the subsequence.[4, 4, 4]then gives 3. - "How many longest increasing subsequences are there?" Extend the O(n²) version with
count[i], the number of longest subsequences that end ati. Whenbest[j] + 1beatsbest[i], copycount[j]. When it ties, addcount[j]. The prices have just one, but[2, 6, 4, 9]has two:2, 6, 9and2, 4, 9.
What a strong answer covers
Defines the O(n²) state in words. Explains what tails[k] means and why a replace keeps it sorted. Says the final tails is not a real subsequence, and picks bisect_left or bisect_right on purpose.
Open in interactive practice deck →