Sub topic 2
The Tails Array: Smallest Ending Value per Length
This chapter assumes you know the O(n^2) dynamic program for LIS, parent pointers, and binary search on a sorted list. The quadratic DP compares every element with every element before it. The faster method keeps a single summary of the elements seen so far and searches it in O(log n) time.
The Tails Array: Smallest Ending Value per Length
Define tails[k] as the smallest ending value of any strictly increasing subsequence of length k+1 seen so far. A small tail is the best one to keep, because more future elements can extend it.
The tails array is always strictly increasing. Suppose a subsequence of length k+2 ends at value v. Drop its last element and you get a subsequence of length k+1 that ends below v. So tails[k] < tails[k+1]. Because the array is sorted, you can binary search it.
O(n log n) LIS with Binary Search
For each element x, find the first slot whose value is >= x. If no slot qualifies, x extends the longest subsequence. Otherwise x replaces that slot and becomes a smaller tail for that length.
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])) # 4| x | tails after x |
|---|---|
| 10 | [10] |
| 9 | [9] |
| 2 | [2] |
| 5 | [2, 5] |
| 3 | [2, 3] |
| 7 | [2, 3, 7] |
| 101 | [2, 3, 7, 101] |
| 18 | [2, 3, 7, 18] |
Reconstructing the Subsequence in O(n log n)
To recover a real subsequence, store the index held in each slot. When x lands in slot k, its predecessor is whatever sits in slot k-1 at that moment.
from bisect import bisect_left
def lis_sequence(a):
tails_val = []
tails_idx = []
parent = [-1] * len(a)
for i, x in enumerate(a):
k = bisect_left(tails_val, x)
if k > 0:
parent[i] = tails_idx[k - 1]
if k == len(tails_val):
tails_val.append(x)
tails_idx.append(i)
else:
tails_val[k] = x
tails_idx[k] = i
seq = []
i = tails_idx[-1] if tails_idx else -1
while i != -1:
seq.append(a[i])
i = parent[i]
return seq[::-1]
print(lis_sequence([10, 9, 2, 5, 3, 7, 101, 18])) # [2, 3, 7, 18]The parent links are fixed at insertion time, so later overwrites of tails don't break the chains you have already recorded.
Exercise
What is the tails array after processing [3, 1, 4, 1, 5], and what LIS length does it give?
Show answer
[3] → [1] → [1, 4] → [1, 4] (the second 1 replaces slot 0 with an equal value) → [1, 4, 5]. The LIS length is 3.
Exercise
Why does lissequence start its walk from tailsidx[-1] and not from the index of the largest value in a?
Show answer
tails_idx[-1] is the end of a subsequence of maximum length. The largest value may end a shorter subsequence. In [5, 1, 2, 3], for example, 5 is the largest value but ends a subsequence of length 1.