Sub topic 7
Reconstructing the Subsequence in O(n log n)
This chapter assumes you already know the O(n log n) tails-array algorithm for LIS length and the parent-pointer reconstruction used in the O(n^2) dynamic program. Here we combine the two so the fast algorithm returns an actual subsequence, not only its length.
Why the tails array is not the answer
When the loop finishes, tails has the right length, but its contents are usually not a valid subsequence. Each slot keeps the smallest ending value seen so far for that length, and different slots get overwritten at different times. As a result, the values in tails can come from positions that are out of order in the input.
Take [3, 4, 1]. The final tails is [1, 4], and the input has no subsequence 1, 4 because the 1 comes after the 4. The correct answer is [3, 4].
The idea: store indices and remember the predecessor
Two changes fix this:
- Keep a parallel array
tails_idx, wheretails_idx[k]is the input index of the element currently sitting in slotk. - When element
ilands in slotk, recordparent[i] = tails_idx[k - 1]. That is the index of the element that currently ends the best subsequence one shorter.
This pointer is valid for two reasons. Because bisect_left returned k, the value tails_val[k - 1] is strictly less than x. That element also appears earlier in the input, since every index in tails_idx has already been processed. So element i extends a real increasing subsequence of length k into one of length k + 1. Slot k - 1 may be overwritten later, but that does not matter: parent[i] saved the index that was there at the moment i was placed.
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 binary search runs over tails_val because values are what stay sorted. The indices in tails_idx are only carried along with them. The walk back starts at tails_idx[-1], which ends a subsequence of maximum length. Each step follows one parent pointer, and the list is reversed at the end because it was built from the last element to the first.
Tracing the example
| 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] |
The walk starts at index 7. It goes 7 → 5 → 4 → 2 → -1, which gives the values 18, 7, 3, 2. Reversed, that is [2, 3, 7, 18].
The parent pointers form a forest of trees. Any path from a leaf at the deepest level back to a root is a valid LIS. This run returns [2, 3, 7, 18], while the O(n^2) version returned [2, 5, 7, 101]. Both have length 4. Which one you get depends on how each algorithm breaks ties.
Cost
The extra work per element is constant: one assignment to parent and one to tails_idx. The total time stays O(n log n). The walk back adds O(L), where L is the LIS length. Space is O(n) for parent.
Common errors
- Returning
tails_valinstead of walking the parent pointers. - Setting
parent[i]after the slot has been updated. Whenk == 0,tails_idx[k - 1]istails_idx[-1]in Python, which silently picks the wrong slot. Theif k > 0guard prevents this. - Starting the walk from the largest value or the last input index instead of from
tails_idx[-1]. - Forgetting to reverse the collected values.
- Running
bisect_leftontails_idx. Indices are not sorted by value, so the search gives wrong positions.
Exercise
Run lissequence on [3, 4, 1]. Give the final tailsval, tails_idx, and parent arrays, and the returned subsequence.
Show answer
tailsval = [1, 4], tailsidx = [2, 1], parent = [-1, 0, -1]. The walk starts at tailsidx[-1] = 1 (value 4), then follows parent[1] = 0 (value 3), then -1. Reversed, the result is [3, 4], even though tailsval is [1, 4].
Exercise
Why is it safe for parent[i] to point at an index whose tails slot is later overwritten?
Show answer
The pointer records a fixed fact: at the time i was placed, a[parent[i]] < a[i], parent[i] < i, and parent[i] ended an increasing subsequence of length k. Later overwrites change only tails_idx. They do not change parent or the chain already stored behind parent[i], so the path from i stays valid.