Sub topic 6
O(n log n) LIS with Binary Search
This chapter turns the tails array from the previous chapter into a complete O(n log n) algorithm. It assumes you can read Python, know Big-O notation, can write a binary search over a sorted list, and have seen the O(n^2) dynamic program, where dp[i] is the length of the longest increasing subsequence ending at index i. The examples here compute only the length of a strictly increasing subsequence. Recovering the actual elements and handling the non-decreasing variant each get their own chapter later.
From the Invariant to an Algorithm
Recall the definition. After processing some prefix of the input, tails[k] holds the smallest value that can end a strictly increasing subsequence of length k + 1 within that prefix. The previous chapter showed that tails is always strictly increasing. The question for this chapter is how to update tails cheaply when the next element x arrives.
The quadratic DP answers "what is the longest subsequence I can extend with x?" by scanning every earlier index. The tails array lets you answer the same question with a single lookup. The subsequences that x can extend are exactly the lengths k + 1 with tails[k] < x. Because tails is sorted, those lengths form a prefix of the array. The first position whose value is >= x marks where that prefix ends, and binary search finds that position in O(log n).
Call that position i. Then:
tails[0..i-1]are all< x, soxcan extend a subsequence of lengthi(ending attails[i-1]) into one of lengthi + 1.tails[i], if it exists, is>= x, soxcannot extend a subsequence of lengthi + 1.
So the longest subsequence ending at x has length i + 1. In the quadratic DP's terms, dp at this index equals i + 1. The update follows directly:
- If
i == len(tails),xis larger than every tail and creates a new, longer subsequence. Append it. - Otherwise,
xends a subsequence of lengthi + 1andx <= tails[i]. Overwritetails[i]withx, because the smaller ending value is at least as useful later.
The Implementation
Python's bisect_left(tails, x) returns exactly the "first index with tails[i] >= x" that the update rule needs.
from bisect import bisect_left
def lis_length(a):
tails = [] # tails[k] = smallest tail of any increasing subsequence of length k+1
for x in a:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
print(lis_length([10, 9, 2, 5, 3, 7, 101, 18])) # 4The function has no special case for an empty input. The loop body never runs and len([]) is 0, which is the correct answer.
Tracing the Example
Here is every step on [10, 9, 2, 5, 3, 7, 101, 18].
| Step | x | `bisect_left` result i | Action | tails after |
|---|---|---|---|---|
| 1 | 10 | 0 | append | [10] |
| 2 | 9 | 0 | replace tails[0] | [9] |
| 3 | 2 | 0 | replace tails[0] | [2] |
| 4 | 5 | 1 | append | [2, 5] |
| 5 | 3 | 1 | replace tails[1] | [2, 3] |
| 6 | 7 | 2 | append | [2, 3, 7] |
| 7 | 101 | 3 | append | [2, 3, 7, 101] |
| 8 | 18 | 3 | replace tails[3] | [2, 3, 7, 18] |
The final length is 4. Steps 2 and 3 show why replacing pays off. After seeing 10, 9, and 2, the best length-1 subsequence to keep is [2], because more future values can follow 2 than can follow 10. Step 5 does the same at length 2: [2, 3] beats [2, 5] as a prefix, and that is what later allows 18 to take the length-4 slot that 101 had held.
Each i in the table, plus one, matches the quadratic DP's dp value at that index. For example, at step 6 the element 7 has dp = 3, from [2, 5, 7] or [2, 3, 7].
Why It Is Correct
The argument has two parts.
The update preserves the invariant. Suppose tails is correct for the prefix before x. Only lengths that x can end change, and the only new candidate ending value is x itself. The longest subsequence x can end has length i + 1. For a shorter length j + 1 with j < i, x is also a candidate, but tails[j] < x already, so nothing changes there. At length i + 1, x <= tails[i], so x becomes the new minimum. If that slot did not exist, appending creates it. Sortedness also holds after a replace, because tails[i-1] < x <= tails[i] < tails[i+1].
The final length is the answer. Slot k exists exactly when some increasing subsequence of length k + 1 exists in the processed prefix. After the whole input, the number of slots is therefore the length of the longest increasing subsequence.
Complexity
| Algorithm | Time | Extra space |
|---|---|---|
| Brute force over subsequences | O(2^n · n) | O(n) |
| Quadratic DP | O(n^2) | O(n) |
| Tails array with binary search | O(n log L) ⊆ O(n log n) | O(L) |
Here L is the LIS length. Each binary search runs over at most L entries, so the bound is O(n log L). The array never grows beyond L entries, which is less memory than the n-entry dp array when the answer is short. For comparison-based algorithms, Ω(n log n) is a known lower bound in the worst case, so this method is asymptotically optimal in that model.
In practice, with n = 10^5 the quadratic DP performs about 5 × 10^9 inner-loop steps, which is far too slow in Python. The tails method does about 1.7 million comparisons and finishes in well under a second.
Writing the Binary Search Yourself
Interviews and languages without bisect often require you to write the search by hand. The safest form uses a half-open range [lo, hi) and searches for the first index whose value is >= x:
def lis_length_manual(a):
tails = []
for x in a:
lo, hi = 0, len(tails) # search in [lo, hi)
while lo < hi:
mid = (lo + hi) // 2
if tails[mid] < x:
lo = mid + 1 # tails[mid] can be extended by x; answer is to the right
else:
hi = mid # tails[mid] >= x; mid might be the answer
if lo == len(tails):
tails.append(x)
else:
tails[lo] = x
return len(tails)
print(lis_length_manual([10, 9, 2, 5, 3, 7, 101, 18])) # 4
print(lis_length_manual([])) # 0
print(lis_length_manual([2, 2, 2])) # 1Starting hi at len(tails), not len(tails) - 1, lets the search return "past the end", and that result triggers the append case.
Common Errors
Other mistakes come up often:
- Using
bisect_rightby accident. For[2, 2, 2],bisect_rightreturns past the existing 2 and appends, which gives 3. That is the answer for non-decreasing subsequences, not strictly increasing ones. A later chapter covers this choice on purpose. - Comparing with
<=in a hand-written search. Writingif tails[mid] <= xturns the search intobisect_rightand has the same effect as the bullet above. - Inserting instead of replacing.
tails.insert(i, x)makes the array grow on every element, and each insert costs O(n), which ruins the time bound as well. - Returning
tails[-1]ormax(tails). The answer is the number of entries, not any value stored in them. - Assuming the input is a list of numbers. The algorithm works for any values with a total order: strings, tuples, or dates. Mixing types that Python cannot compare raises a
TypeErrorinsidebisect_left.
Testing Against the Quadratic DP
The quadratic DP is easy to get right, so it is a good reference for randomized testing. Small value ranges create many duplicates, and duplicates are where strictness bugs show up.
import random
from bisect import bisect_left
def lis_length_quadratic(a):
if not a:
return 0
dp = [1] * len(a)
for i in range(len(a)):
for j in range(i):
if a[j] < a[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
return max(dp)
def lis_length(a):
tails = []
for x in a:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
random.seed(1)
for _ in range(2000):
n = random.randint(0, 12)
a = [random.randint(0, 5) for _ in range(n)]
assert lis_length(a) == lis_length_quadratic(a), a
print("all tests passed")Exercises
Exercise
Trace lis_length on [0, 8, 4, 12, 2, 10, 6, 14, 1, 9]. Give the tails array after every element and the final answer.
Show answer
[0] → [0, 8] → [0, 4] → [0, 4, 12] → [0, 2, 12] → [0, 2, 10] → [0, 2, 6] → [0, 2, 6, 14] → [0, 1, 6, 14] → [0, 1, 6, 9]. The answer is 4, for example from [0, 4, 6, 9] or [0, 2, 6, 9]. The final tails [0, 1, 6, 9] is not itself a subsequence, because the 1 appears after the 6 in the input.
Exercise
A colleague's hand-written search initializes hi = len(tails) - 1 and loops while lo <= hi, using the same body as lislengthmanual. What goes wrong when x is larger than every element of tails?
Show answer
With the closed range [lo, hi], the update hi = mid can loop forever when lo == hi == mid and tails[mid] >= x, so the body has to be changed to hi = mid - 1. Even after that fix, the search must still be able to return len(tails) when x exceeds every tail, or the append case never fires. The half-open form with hi = len(tails) and lo < hi handles both cases with no special handling.
Exercise
Explain why the overwrite step tails[i] = x can never make tails unsorted.
Show answer
bisect_left guarantees tails[i-1] < x (if i > 0) and x <= tails[i]. Since tails[i] < tails[i+1] already held, the new value sits strictly between its neighbors: tails[i-1] < x <= tails[i] < tails[i+1]. The array therefore stays strictly increasing.