Sub topic 7
Reconstructing the Subsequence in O(n log n)
The binary-search algorithm from the previous chapter gives you the length of the longest increasing subsequence in O(n log n) time. Most real tasks need the subsequence itself, though. You might need to print it, check it, or pass it to the next step. This chapter adds a small amount of bookkeeping to the tails-array method so it returns an actual longest strictly increasing subsequence, with no change to its time complexity.
This chapter assumes you know:
- the
tailsinvariant:tails[k]is the smallest value that ends any increasing subsequence of lengthk + 1, andtailsstays sorted; - how
bisect_leftfinds the slot for each new element; - parent pointers from the O(n²) reconstruction chapter.
Why the tails array alone is not an answer
At the end of the algorithm, tails has the right length. It is tempting to return it as the subsequence, and that is wrong. Each slot is overwritten independently, so the final contents of tails can mix values from different subsequences, and they may not even appear in the right order in the input.
from bisect import bisect_left
def tails_only(a):
tails = []
for x in a:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return tails
print(tails_only([3, 4, 5, 1])) # [1, 4, 5]The output [1, 4, 5] has length 3, which is correct. It is still not a subsequence of [3, 4, 5, 1], because 1 comes after 4 and 5 in the input. A valid answer is [3, 4, 5].
The idea: freeze the predecessor at insertion time
When element x at index i lands in slot k, the algorithm has just shown that x extends some increasing subsequence of length k. That subsequence ends at whatever element currently sits in slot k - 1. The invariant guarantees two facts about that element:
- Its value is less than
x, becausebisect_leftreturnedk, sotails[k - 1] < x. - Its index is less than
i, because it was placed during an earlier iteration.
So that element is a legal predecessor of x. Record its index as parent[i] now. Later iterations may overwrite slot k - 1, but parent[i] is already stored and does not change. This frozen pointer is what makes reconstruction work. The tails array changes all the time, but each element's link to its predecessor is fixed when the element is processed.
To record a predecessor's index, the tails structure must store indices as well as values. We keep two parallel lists:
| List | Meaning |
|---|---|
| `tails_val[k]` | smallest ending value of an increasing subsequence of length `k + 1` seen so far |
| `tails_idx[k]` | index in `a` of the element holding `tails_val[k]` |
| `parent[i]` | index of the element before `a[i]` in the subsequence that `a[i]` extended, or `-1` |
The implementation
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]
print(lis_sequence([3, 4, 5, 1])) # [3, 4, 5]
print(lis_sequence([])) # []Reconstruction starts from tails_idx[-1]. The last slot holds the end of a subsequence whose length equals the LIS length. The parent chain from that element has exactly that many links, because each link drops one slot, from k to k - 1, until it reaches slot 0, where the parent is -1.
Statement order inside the loop
The parent is read from slot k - 1 and the write goes to slot k. These are different slots, so the order of the two if blocks does not affect correctness. It is still clearest to read the predecessor before modifying anything. That habit matters if you later change the code so the two slots can coincide.
Tracing the example
Here is every step for a = [10, 9, 2, 5, 3, 7, 101, 18]:
| i | x | k | parent[i] | tails_val after | tails_idx after |
|---|---|---|---|---|---|
| 0 | 10 | 0 | -1 | [10] | [0] |
| 1 | 9 | 0 | -1 | [9] | [1] |
| 2 | 2 | 0 | -1 | [2] | [2] |
| 3 | 5 | 1 | 2 | [2, 5] | [2, 3] |
| 4 | 3 | 1 | 2 | [2, 3] | [2, 4] |
| 5 | 7 | 2 | 4 | [2, 3, 7] | [2, 4, 5] |
| 6 | 101 | 3 | 5 | [2, 3, 7, 101] | [2, 4, 5, 6] |
| 7 | 18 | 3 | 5 | [2, 3, 7, 18] | [2, 4, 5, 7] |
Walking back from tails_idx[-1] = 7 gives index 7 (value 18), then 5 (value 7), then 4 (value 3), then 2 (value 2), then -1. Reversed, the answer is [2, 3, 7, 18].
Look at index 6, value 101. Its parent pointer still leads to a valid subsequence, [2, 3, 7, 101], even though 101 was later pushed out of slot 3. Each element's parent chain stays a valid increasing subsequence permanently.
The parent pointers form a forest: each element points to at most one earlier element. Every root-to-node path in this forest is an increasing subsequence.
Which LIS do you get?
The quadratic version from the earlier chapter returned [2, 5, 7, 101] for the same input. This version returns [2, 3, 7, 18]. Both are correct. An input often has several longest increasing subsequences, and different algorithms return different ones.
This algorithm prefers small values. The final element is the smallest value that can end an LIS, because that is what tails_val[-1] holds. Each predecessor is whatever element held the previous slot at the moment the successor arrived. That predecessor is the smallest value ending a subsequence of that length among the elements seen up to then.
If a problem requires a specific LIS, such as the lexicographically smallest one or the one with the earliest indices, do not assume this code produces it. Work out the tie-breaking rule and test it.
Complexity
| Resource | Cost | Source |
|---|---|---|
| Time | O(n log n) | one `bisect_left` per element, plus an O(L) walk back |
| Extra space | O(n) | the `parent` array; `tails_val` and `tails_idx` are O(L) |
Reconstruction adds O(n) memory for parent. If you only need the length, drop parent and tails_idx to get O(L) space.
A variant that stores only indices
From Python 3.10, bisect functions accept a key argument. The key is applied to list elements but not to the search value. That lets you keep a single list of indices:
from bisect import bisect_left
def lis_sequence_idx(a):
tails = [] # indices into a
parent = [-1] * len(a)
for i, x in enumerate(a):
k = bisect_left(tails, x, key=lambda j: a[j])
if k > 0:
parent[i] = tails[k - 1]
if k == len(tails):
tails.append(i)
else:
tails[k] = i
seq = []
i = tails[-1] if tails else -1
while i != -1:
seq.append(a[i])
i = parent[i]
return seq[::-1]
print(lis_sequence_idx([10, 9, 2, 5, 3, 7, 101, 18])) # [2, 3, 7, 18]This version has less state to keep in sync. On older Python versions, or when speed matters, the two-list version is safer: the key lambda runs once per comparison and adds overhead.
Common errors
- Returning
tails_val. The length is right, but the contents may not be a subsequence, as[3, 4, 5, 1]showed. - Using
tails_idx[k]as the parent. Slotkholds an element of the same length asx, not the one before it. Usek - 1. - Starting the walk at the index of the maximum value. The largest value need not end an LIS. Always start from
tails_idx[-1]. - Building the chain from current
tails_idxat the end. Followingtails_idx[L-1], tails_idx[L-2], ...repeats the first mistake using indices. Onlyparentlinks are guaranteed consistent. - Forgetting the empty input.
tails_idx[-1]raisesIndexErroron[]. The guardif tails_idx else -1handles it. - Forgetting to reverse. The walk goes from the end to the start.
Edge cases
| Input | Result | Why |
|---|---|---|
| `[]` | `[]` | no slots, walk starts at -1 |
| `[7]` | `[7]` | one slot, parent -1 |
| `[5, 5, 5]` | `[5]` | strict: each 5 replaces slot 0 |
| `[4, 3, 2, 1]` | `[1]` | every element lands in slot 0; the last one wins |
| `[1, 2, 3, 4]` | `[1, 2, 3, 4]` | every element appends |
For the non-decreasing variant, change bisect_left to bisect_right. The predecessor in slot k - 1 then satisfies tails_val[k - 1] <= x, and the same parent logic produces a valid non-decreasing subsequence. The next chapter covers why that one-word change is correct.
Testing your reconstruction
A reconstructed sequence must pass two checks. Its length must equal the LIS length, and it must actually be a strictly increasing subsequence of the input. A randomized comparison against the quadratic DP tests both:
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_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]
def is_subsequence(seq, a):
it = iter(a)
return all(any(v == y for y in it) for v in seq)
def is_strictly_increasing(seq):
return all(p < q for p, q in zip(seq, seq[1:]))
for _ in range(2000):
a = [random.randint(0, 9) for _ in range(random.randint(0, 12))]
s = lis_sequence(a)
assert len(s) == lis_length_quadratic(a), (a, s)
assert is_subsequence(s, a), (a, s)
assert is_strictly_increasing(s), (a, s)
print("all checks passed")Small values such as 0..9 produce many duplicates, which is where strict-versus-non-strict bugs show up. Keep the arrays short so failures are easy to read.
Exercise
Run lis_sequence on [2, 6, 3, 4, 1, 5]. Give the parent array and the returned subsequence.
Show answer
The slots evolve as follows. i=0 (2) goes to k=0, parent -1. i=1 (6) goes to k=1, parent 0. i=2 (3) goes to k=1, parent 0, and replaces 6. i=3 (4) goes to k=2, parent 2. i=4 (1) goes to k=0, parent -1, and replaces 2. i=5 (5) goes to k=3, parent 3. So parent = [-1, 0, 0, 2, -1, 3], and the walk from tailsidx[-1] = 5 gives 5, 3, 2, 0, which is the subsequence [2, 3, 4, 5]. The final tailsval is [1, 3, 4, 5], which is not a valid subsequence, because 1 comes after 3 and 4 in the input.
Exercise
A teammate changes the line parent[i] = tailsidx[k - 1] to parent[i] = tailsidx[k] (guarded by k < len(tails_idx)). Give a short input where the result is wrong, and explain why.
Show answer
Try [1, 2]. For i=1 (value 2), k=1 and len(tails_idx) is 1, so the guard fails and parent[1] stays -1. The walk returns [2] instead of [1, 2]. Slot k holds an element that ends a subsequence of the same length as x, so it can never be x's predecessor. When the guard does pass, the pointer goes to an element of equal or greater value, which breaks the increasing order.
Exercise
Why is it safe for later iterations to overwrite tails_idx[k - 1] after parent[i] has been set to it?
Show answer
parent[i] stores an index, not a reference to the slot. The element at that index already satisfied value < x and index < i when it was recorded, and its own parent chain was fixed when it was processed. Overwriting the slot only changes which element future elements will see. It cannot change any pointer already stored, so every existing chain stays a valid increasing subsequence.