Sub topic 4
Recovering the Subsequence with Parent Pointers
The O(n^2) dynamic program from the previous chapter tells you how long the longest increasing subsequence is. Most real tasks also need the subsequence itself, for example to print it, to check it, or to pass it to the next step of a pipeline. This chapter adds one extra array to the DP so you can walk back through the choices it made and rebuild an optimal subsequence.
This chapter assumes you know basic Python and the recurrence dp[i] = 1 + max(dp[j] for j < i with a[j] < a[i]), where dp[i] is the length of the longest strictly increasing subsequence that ends at index i. Big-O notation is used without explanation.
Why the dp Array Alone Is Not Enough
After the DP finishes, dp holds one number per index. For a = [10, 9, 2, 5, 3, 7, 101, 18] it is [1, 1, 1, 2, 2, 3, 4, 4]. You can see that some subsequence of length 4 ends at index 6 (value 101). The array does not record which earlier element came before 101. Several earlier indices may have the right length and a smaller value, and the DP picked one of them without saving that choice.
There are two ways to get the subsequence back:
- Record each choice as the DP makes it. This is the parent-pointer method.
- Rebuild the choices afterwards by searching the finished
dparray.
Both take O(n^2) time overall, because the DP itself does. They differ in extra memory and in which optimal subsequence they return.
Parent Pointers: Record the Winning Predecessor
A parent pointer is an index stored next to each dp[i]. It names the j that produced the current value of dp[i]. If no earlier element extended into i, so that i starts its own subsequence, the pointer is -1.
Update the pointer only when dp[i] improves. The pointer has to describe the same choice that produced the stored length.
def lis_sequence_quadratic(a):
if not a:
return []
n = len(a)
dp = [1] * n
parent = [-1] * n
for i in range(n):
for j in range(i):
if a[j] < a[i] and dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
parent[i] = j
i = max(range(n), key=lambda k: dp[k])
seq = []
while i != -1:
seq.append(a[i])
i = parent[i]
return seq[::-1]
print(lis_sequence_quadratic([10, 9, 2, 5, 3, 7, 101, 18])) # [2, 5, 7, 101]Reconstruction has three steps:
- Find an end index whose
dpvalue is the maximum. The longest subsequence has to end at such an index. - Follow
parentfrom that index until you reach-1, collecting values as you go. - Reverse the collected list, because the walk goes from the last element back to the first.
The walk visits at most L indices, where L is the LIS length, so it costs O(L). The parent array adds O(n) memory.
Tracing the Example
The table shows the state after the DP finishes on [10, 9, 2, 5, 3, 7, 101, 18].
| i | a[i] | dp[i] | parent[i] | Why |
|---|---|---|---|---|
| 0 | 10 | 1 | -1 | Nothing before it |
| 1 | 9 | 1 | -1 | 10 is not smaller |
| 2 | 2 | 1 | -1 | No smaller earlier value |
| 3 | 5 | 2 | 2 | Extends 2 |
| 4 | 3 | 2 | 2 | Extends 2 |
| 5 | 7 | 3 | 3 | j=3 gives 3 first; j=4 ties and is rejected by `>` |
| 6 | 101 | 4 | 5 | Extends 7 |
| 7 | 18 | 4 | 5 | Extends 7 |
max(range(n), key=...) returns the first index holding the maximum, which is index 6. The walk goes 6 → 5 → 3 → 2 → -1 and collects 101, 7, 5, 2. Reversed, that gives [2, 5, 7, 101].
The pointers form a forest of trees whose roots are the -1 entries. Each path from a node to a root is an increasing subsequence read backwards, and its length equals that node's dp value. Reconstruction picks the deepest node and reads its path.
Which Optimal Subsequence You Get
An array often has many longest increasing subsequences. This example has several of length 4, including [2, 5, 7, 101], [2, 3, 7, 18] and [2, 5, 7, 18]. Two small decisions in the code determine which one is returned.
| Decision | Choice in the code | Effect |
|---|---|---|
| Tie between predecessors | `dp[j] + 1 > dp[i]` (strict) | Keeps the earliest `j` that reached the best length |
| Tie between predecessors | `dp[j] + 1 >= dp[i]` | Keeps the latest such `j` |
| Tie between end indices | `max(...)` | First index with the maximum `dp` |
| Tie between end indices | Scan from the right for the max | Last index with the maximum `dp` |
All four combinations return a valid LIS. None of them guarantees the lexicographically smallest one. If you need a canonical answer, such as for deterministic test output or a problem statement that asks for "the smallest", choose the tie-breaking rule on purpose and test it. Don't rely on whatever falls out of the loop order.
Reconstruction Without a Parent Array
The finished dp array has enough information to rebuild a subsequence without storing pointers. Walk from right to left looking for values with dp equal to L, then L−1, then L−2, and so on. Each value you take must be smaller than the one taken before it.
def lis_sequence_from_dp(a, dp):
if not a:
return []
need = max(dp)
last = None
seq = []
for i in range(len(a) - 1, -1, -1):
if dp[i] == need and (last is None or a[i] < last):
seq.append(a[i])
last = a[i]
need -= 1
if need == 0:
break
return seq[::-1]
a = [10, 9, 2, 5, 3, 7, 101, 18]
dp = [1, 1, 1, 2, 2, 3, 4, 4]
print(lis_sequence_from_dp(a, dp)) # [2, 3, 7, 18]This greedy scan never gets stuck. If you take index i with dp[i] = k, then by the definition of dp some earlier j has dp[j] = k - 1 and a[j] < a[i]. A later pass of the scan will reach it. The scan is one pass, O(n), and needs no extra array. The cost is that the DP and the reconstruction rules must agree exactly. If you change the comparison to <= for a non-decreasing variant, you have to change a[i] < last to a[i] <= last as well.
Use parent pointers when you want the reconstruction to follow the DP's own choices and stay simple to reason about. Use the backward scan when memory is tight, or when dp was computed elsewhere and you only have its values.
Common Errors
- Updating
parentoutside the improvement branch. Ifparent[i] = jruns on everyjwitha[j] < a[i], the pointer ends up naming the last smaller element, not the one that produceddp[i]. The rebuilt sequence can then be shorter thanmax(dp). - Starting the walk at
n - 1. The LIS does not have to end at the last element. For[3, 4, 1]the walk from index 2 gives[1]. Always start from an index wheredpis the maximum. - Forgetting to reverse. The walk produces the subsequence from last element to first.
- Storing values instead of indices. Pointers must be indices. With duplicates, such as
[2, 2, 3], a value cannot tell you which position it came from. - Empty input.
max(range(0), ...)raisesValueError. Guard withif not a.
Testing Reconstruction Properly
Checking only the length of the output misses most reconstruction bugs. A correct output has to pass three checks: it is a subsequence of the input, it is strictly increasing, and its length equals the brute-force optimum. The harness below applies all three to random small arrays, using lis_sequence_quadratic from earlier.
import random
from itertools import combinations
def is_subsequence(seq, a):
it = iter(a)
return all(any(x == y for y in it) for x in seq)
def brute_lis_length(a):
for r in range(len(a), 0, -1):
for idx in combinations(range(len(a)), r):
vals = [a[k] for k in idx]
if all(vals[t] < vals[t + 1] for t in range(r - 1)):
return r
return 0
for _ in range(500):
a = [random.randint(0, 6) for _ in range(random.randint(0, 9))]
s = lis_sequence_quadratic(a)
assert is_subsequence(s, a)
assert all(s[t] < s[t + 1] for t in range(len(s) - 1))
assert len(s) == brute_lis_length(a), (a, s)
print("all checks passed")The small value range from 0 to 6 produces many duplicates, which is where strictness bugs show up. Some edge cases are worth adding as fixed tests: [] gives [], [5, 5, 5] gives [5], and a strictly decreasing array such as [4, 3, 2, 1] gives [4], its first element.
Exercise
Run lissequencequadratic on [10, 9, 2, 5, 3, 7, 101, 18], but replace max(range(n), key=...) with code that picks the last index holding the maximum dp value. What subsequence is returned, and why is it still correct?
Show answer
The last index with dp = 4 is 7 (value 18). Its parent is 5 (7), then 3 (5), then 2 (2), so the result is [2, 5, 7, 18]. It is correct because every index with the maximum dp value ends some longest increasing subsequence, and the parent chain from that index always has length dp[i].
Exercise
A student writes if a[j] < a[i]: parent[i] = j followed by a separate if a[j] < a[i] and dp[j] + 1 > dp[i]: dp[i] = dp[j] + 1. Give an input where the reconstructed sequence is shorter than max(dp).
Show answer
Use [1, 2, 0, 3]. dp becomes [1, 2, 1, 3], but parent[3] = 2, because 0 is the last smaller element before 3. The walk from index 3 gives [0, 3], length 2, while max(dp) is 3. The pointer must change only when dp[i] improves.
Exercise
Modify lissequencefrom_dp so it works with a dp array computed for the longest non-decreasing subsequence (where the DP uses a[j] <= a[i]). What single change is needed, and what does it return for a = [1, 3, 3, 2, 3] with dp = [1, 2, 3, 2, 4]?
Show answer
Change the condition a[i] < last to a[i] <= last. Scanning from the right: index 4 (3, dp 4) is taken, then index 2 (3, dp 3), then index 1 (3, dp 2), then index 0 (1, dp 1). The result is [1, 3, 3, 3].