Sub topic 6
O(n log n) LIS with Binary Search
This chapter assumes you know the tails array from the previous chapter: tails[k] holds the smallest ending value of any strictly increasing subsequence of length k + 1 seen so far, and the array is always sorted. It also assumes you can use binary search on a sorted list and read Big-O notation. Here we turn that invariant into an algorithm that runs in O(n log n) time.
The Core Idea
The quadratic DP compares each element with every earlier element. The tails array removes that need. Because tails is sorted, one binary search per element finds where the element belongs:
- If
xis larger than every tail, it extends the longest subsequence so far. Append it. - Otherwise, find the first tail that is greater than or equal to
xand replace that tail withx. A subsequence of that length can now end on a smaller value, which leaves more room for later elements to extend it.
When the loop finishes, len(tails) is the length of the LIS.
The Implementation
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])) # 4bisect_left(tails, x) returns the first index i where tails[i] >= x. Every tail before i is strictly less than x, so x can extend the subsequence of length i and become the new best tail for length i + 1.
Why the Invariant Survives
Before a replacement, tails[i-1] < x <= tails[i]. After setting tails[i] = x, the value x is still greater than tails[i-1], and it is no larger than the old tails[i], which was smaller than tails[i+1]. The array stays sorted, so the next binary search is still valid. An append happens only when x exceeds the last tail, so appending also keeps the array sorted.
A Full Trace
Input: [10, 9, 2, 5, 3, 7, 101, 18]
| x | bisect_left index | Action | tails after |
|---|---|---|---|
| 10 | 0 | append | [10] |
| 9 | 0 | replace 10 | [9] |
| 2 | 0 | replace 9 | [2] |
| 5 | 1 | append | [2, 5] |
| 3 | 1 | replace 5 | [2, 3] |
| 7 | 2 | append | [2, 3, 7] |
| 101 | 3 | append | [2, 3, 7, 101] |
| 18 | 3 | replace 101 | [2, 3, 7, 18] |
The final length is 4, which matches the quadratic DP.
Common Errors
- Using
bisect_rightby mistake. For strictly increasing subsequences, an equal value must replace the existing tail, not extend past it. Withbisect_right, the input[2, 2]would return 2 instead of 1. A later chapter covers whenbisect_rightis the right choice. - Writing binary search by hand with off-by-one bounds. If you can't use
bisect, search for the first index withtails[i] >= xover the half-open range[0, len(tails)).
Cost
Each of the n elements triggers one binary search over at most L tails, where L is the LIS length. Time is O(n log L), which is O(n log n). Extra space is O(L) for the tails array.
To check the fast version, compare it against the quadratic DP on random inputs:
import random
from bisect import bisect_left
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)
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)
for _ in range(1000):
a = [random.randint(0, 20) for _ in range(random.randint(0, 30))]
assert lis_length(a) == lis_length_quadratic(a), a
print("all tests passed")The small value range (0 to 20) produces many duplicates, so the test also checks that equal values are handled strictly.
Exercise
Trace lis_length on [0, 8, 4, 12, 2, 10, 6, 14, 1, 9]. What is the final tails array and the returned length?
Show answer
The tails array evolves as [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 final tails array is [0, 1, 6, 9] and the length is 4. The final array is not itself a valid subsequence, because 1 appears after 6 in the input. One real LIS is [0, 4, 6, 9].
Exercise
Why does replacing tails[i] with x never shorten the answer, even though it overwrites a value?
Show answer
The length of tails never decreases, because a replacement leaves len(tails) unchanged. Replacing tails[i] with the smaller x only lowers the best ending value for length i+1. Any later element that could have extended the old tail can also extend x, so no future extension is lost.