Reconstructing Solutions & Saving Space
Parent pointers, rolling arrays and Hirschberg’s linear-space trick.
Comparing two strings of 100,000 letters with an LCS table means cells: about 10 GB even at one byte per cell, just to remember the decisions, while the length alone needs two rows of the table. In 1975 Dan Hirschberg showed how to recover an optimal common subsequence itself in linear space, for about twice the time of one plain fill. This lesson is about getting the solution, not just its value, and about how little memory that really takes.
What you’ll learn
- Recover an optimal solution from a filled table, either by recomputing each decision or from stored parent pointers, and prove the traceback correct.
- Cut space with rolling arrays (two rows for LCS, one row scanned downward for 0/1 knapsack) and explain what each one loses.
- Prove Hirschberg's split lemma, and show that his divide and conquer finds an LCS in time and space.
- Trade time for space with checkpoints, and relate DP space reduction to general time–space simulations.
From values to solutions
A filled table holds the optimal value of every subproblem. The solution itself is the chain of choices behind the original problem's value, and there are two ways to recover it:
- Recompute. Start at the original state . At each state , re-evaluate its options from the table and follow any option with , until a base state. No extra memory; each step costs the number of options.
- Parent pointers. While filling, store the winning option of every state, often in 1 or 2 bits. The walk then costs per step, but the pointers take memory proportional to the table, even when a rolling array would hold the values in far less.
def lcs_traceback(a, b):
n, m = len(a), len(b)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1] + 1
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
i, j, out = n, m, []
while i > 0 and j > 0: # recompute each decision from the table
if a[i - 1] == b[j - 1]:
out.append(a[i - 1]); i -= 1; j -= 1
elif dp[i - 1][j] >= dp[i][j - 1]:
i -= 1 # some LCS skips a[i-1]
else:
j -= 1 # some LCS skips b[j-1]
return ''.join(reversed(out))
print(lcs_traceback('CARTOON', 'ACTION')) # CTONCLRS's PRINT-LCS, written as a loop. Taking a match whenever the last letters agree is safe: some LCS uses that match, by an exchange argument. On ties the walk moves up, which is why it returns CTON rather than ATON.
In that knapsack table, items A, B, C, D weigh 2, 3, 4, 5. The traceback stands on , and . What does it do next?
- Pack item B and move to
- Skip item B and move to
- Pack item B and move to
- Stop: the value 5 is final
Show the answer
A. Pack item B and move to
Row 2 adds item B (weight 3, value 5). The value rose from to 5, so B is packed, and the rest must be an optimal packing of the first item within capacity , the cell . From there the walk leaves A out and ends at row 0.
Rolling arrays, and what they forget
A rolling array keeps only the rows the relation still reads. LCS row reads rows and , so two rows of length suffice for the length; putting the shorter string on the columns gives space.
The 0/1 knapsack needs just one row if the capacities are scanned downward: when is updated, must still hold the previous row's value, the best packing without the current item. Scanning upward would let the item build on a value that already includes it, which solves the unbounded knapsack instead.
def knapsack(items, W): # items: (weight, value), each usable once
best = [0] * (W + 1) # best[c]: max value within capacity c
for w, v in items:
for c in range(W, w - 1, -1): # downward: best[c - w] is still the old row
best[c] = max(best[c], best[c - w] + v)
return best[W]
print(knapsack([(2, 3), (3, 5), (4, 7), (5, 8)], 8)) # 13: items B and Dtime and space, with the items of the widget above.
Someone writes the inner loop upward, for c in range(w, W + 1). With a single item of weight 2 and value 3, and capacity , what does the function return?
Show the answer
12
Upward, , then , and : the single item is packed four times. That is the unbounded knapsack. On the four items above, the upward loop returns 14 (item C twice) instead of 13.
Hirschberg: the solution in linear space
Split at its middle row, . An LCS of and passes from the top half to the bottom half at some column , and both halves can be measured in linear space: one forward pass over gives the last row , and one pass over the reversed strings gives .
At least. A common subsequence of the two top pieces followed by one of the two bottom pieces is a common subsequence of and , because in both strings every position of the first lies before every position of the second:
At most. Fix an LCS with its positions in and . The letters of taken from form a prefix , and the rest, , come from . Let be one past the position in of the last letter of ( if is empty). Then is common to and , and to and :
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | |
|---|---|---|---|---|---|---|---|
| : CAR vs | 0 | 1 | 1 | 1 | 1 | 1 | 1 |
| : TOON vs | 3 | 3 | 3 | 2 | 2 | 1 | 0 |
| 3 | 4 | 4 | 3 | 3 | 2 | 1 |
def lcs_row(a, b):
"""Last row of the LCS table: row[j] = LCS(a, b[:j]), in O(len(b)) space."""
prev = [0] * (len(b) + 1)
for x in a:
cur = [0] * (len(b) + 1)
for j, y in enumerate(b, 1):
cur[j] = prev[j - 1] + 1 if x == y else max(prev[j], cur[j - 1])
prev = cur
return prev
def hirschberg(a, b):
"""An LCS of a and b in O(len(a) * len(b)) time and O(len(a) + len(b)) space."""
if not a or not b:
return ''
if len(a) == 1:
return a if a in b else ''
mid = len(a) // 2
F = lcs_row(a[:mid], b) # F[j] = LCS(a[:mid], b[:j])
B = lcs_row(a[mid:][::-1], b[::-1])[::-1] # B[j] = LCS(a[mid:], b[j:])
j = max(range(len(b) + 1), key=lambda k: F[k] + B[k])
return hirschberg(a[:mid], b[:j]) + hirschberg(a[mid:], b[j:])
print(hirschberg('CARTOON', 'ACTION')) # ATONChecked against the full-table LCS on thousands of random DNA strings: same length every time, and always a common subsequence. (Python slices copy the strings; an index-based version keeps the extra space at .)
A call on an problem runs two row passes over about cells each: at most time for a constant . Its two subproblems are and , whose areas add up to half of the parent's:
Guess and substitute: the children contribute at most , so the guess reproduces itself. The work per level halves, a geometric series, so there is no factor of :
Space: two rows of length at a time, a recursion stack of depth , and the answer itself:
Checkpoints and the time–space frontier
Hirschberg's trick relies on the split lemma, which most DPs lack. A general alternative is checkpointing: during the forward fill, keep every -th row; during the traceback, recompute one block of rows at a time from its checkpoint. The forward pass costs , the recomputation another , and memory is values, smallest at :
Applying the idea recursively inside the blocks, with levels, gives space for time ; with that is space for time.
Key takeaways
- A traceback follows, from the original state, any option whose recomputed value equals the stored one. If the options are sound it yields an optimal solution, in steps for LCS-type tables and with no extra memory.
- Rolling arrays keep only the rows a relation reads: two rows for LCS, one downward-scanned row for 0/1 knapsack (scanning upward gives the unbounded knapsack). They lose the traceback.
- Hirschberg's split lemma, , yields an LCS in time and space, because the subproblems' areas halve at every level.
- Checkpointing trades time for space in any DP: time with space, or space with logarithmically many levels, the same idea as gradient checkpointing. General simulations reach space for time (Williams, 2025).
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
After filling an LCS table, what does a traceback by recomputation cost?
- more time, since every cell is revisited
- time and no memory beyond the table
- time, by binary search
- It is impossible without stored parent pointers
Show the answer
B. time and no memory beyond the table
Each step of the walk moves up, left or diagonally, so there are at most steps, and each re-evaluates one cell's options from the table in . Parent pointers would make each step a lookup but cost memory for every cell.
Why does the one-row 0/1 knapsack scan the capacities from down to ?
- It is faster than scanning upward
- So that still holds the value without the current item when is updated
- So that the items are considered in order of decreasing weight
- It does not matter: both directions give the 0/1 answer
Show the answer
B. So that still holds the value without the current item when is updated
Downward, every cell below still belongs to the previous row when is updated, so each item is used at most once. Upward, may already include the item, which allows unlimited copies: the unbounded knapsack.
Hirschberg's algorithm recurses on two subproblems at every level. Why is its total time rather than ?
- Because the recursion depth is constant
- Because the two subproblems' areas add up to half of the parent's, so the work per level halves
- Because it computes only the LCS length, not the LCS itself
- Because each half is solved by a greedy scan
Show the answer
B. Because the two subproblems' areas add up to half of the parent's, so the work per level halves
A call costs about times the area it processes. The children have areas and , together , so the levels cost , , , …, which sum to at most .
In Hirschberg's split, reaches its maximum at two different columns . Which may the algorithm use?
- Only the smaller one
- Only the larger one
- Either one: each yields an optimal split
- Neither: a tie means the strings must be split at another row
Show the answer
C. Either one: each yields an optimal split
By the split lemma the maximum equals the LCS length, and for any maximizing , LCSs of the two subproblems concatenate to a common subsequence of that length. Different choices may return different LCSs, such as ATON and CTON for CARTOON and ACTION, all optimal.
Further reading
- D. S. Hirschberg, "A linear space algorithm for computing maximal common subsequences," Communications of the ACM 18(6) (1975), 341–343.
- E. W. Myers & W. Miller, "Optimal alignments in linear space," Computer Applications in the Biosciences (1988).
- A. Griewank, "Achieving logarithmic growth of temporal and spatial complexity in reverse automatic differentiation," Optimization Methods and Software 1(1) (1992), 35–54.
- R. Williams, "Simulating Time With Square-Root Space," STOC 2025.
- J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapter 6.