Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

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 101010^{10} 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 O(nm)O(nm) time and O(n+m)O(n + m) 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 s0s_0. At each state ss, re-evaluate its options from the table and follow any option oo with go(V(next(o)))=V(s)g_o\big(V(\mathrm{next}(o))\big) = V(s), 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 O(1)O(1) per step, but the pointers take memory proportional to the table, even when a rolling array would hold the values in far less.
python
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'))   # CTON

CLRS'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.

Check your understanding

In that knapsack table, items A, B, C, D weigh 2, 3, 4, 5. The traceback stands on dp[2][3]=5\text{dp}[2][3] = 5, and dp[1][3]=3\text{dp}[1][3] = 3. What does it do next?

  1. Pack item B and move to dp[1][0]\text{dp}[1][0]
  2. Skip item B and move to dp[1][3]\text{dp}[1][3]
  3. Pack item B and move to dp[1][3]\text{dp}[1][3]
  4. Stop: the value 5 is final
Show the answer

A. Pack item B and move to dp[1][0]\text{dp}[1][0]

Row 2 adds item B (weight 3, value 5). The value rose from dp[1][3]=3\text{dp}[1][3] = 3 to 5, so B is packed, and the rest must be an optimal packing of the first item within capacity 3−3=03 - 3 = 0, the cell dp[1][0]=0\text{dp}[1][0] = 0. 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 ii reads rows ii and i−1i - 1, so two rows of length m+1m + 1 suffice for the length; putting the shorter string on the columns gives O(min⁡(n,m))O(\min(n, m)) space.

The 0/1 knapsack needs just one row if the capacities are scanned downward: when best[c]\text{best}[c] is updated, best[c−w]\text{best}[c - w] 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.

python
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 D

O(nW)O(nW) time and O(W)O(W) space, with the items of the widget above.

Predict before you look

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 W=8W = 8, what does the function return?

Show the answer

12

Upward, best[2]=3\text{best}[2] = 3, then best[4]=best[2]+3=6\text{best}[4] = \text{best}[2] + 3 = 6, best[6]=9\text{best}[6] = 9 and best[8]=12\text{best}[8] = 12: 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 aa at its middle row, i=⌊n/2⌋i = \lfloor n/2 \rfloor. An LCS of aa and bb passes from the top half to the bottom half at some column jj, and both halves can be measured in linear space: one forward pass over a[0..i)a[0..i) gives the last row F[j]=LCS(a[0..i),b[0..j))F[j] = \mathrm{LCS}(a[0..i), b[0..j)), and one pass over the reversed strings gives B[j]=LCS(a[i..n),b[j..m))B[j] = \mathrm{LCS}(a[i..n), b[j..m)).

DerivationProof
  1. LCS(a,b) ≥ F[j]+B[j]for every j\mathrm{LCS}(a, b)\ \ge\ F[j] + B[j]\qquad\text{for every } j

    At least. A common subsequence of the two top pieces followed by one of the two bottom pieces is a common subsequence of aa and bb, because in both strings every position of the first lies before every position of the second:

  2. ∣w∣=∣w1∣+∣w2∣ ≤ F[j]+B[j]\abs{w} = \abs{w_1} + \abs{w_2}\ \le\ F[j] + B[j]

    At most. Fix an LCS ww with its positions in aa and bb. The letters of ww taken from a[0..i)a[0..i) form a prefix w1w_1, and the rest, w2w_2, come from a[i..n)a[i..n). Let jj be one past the position in bb of the last letter of w1w_1 (j=0j = 0 if w1w_1 is empty). Then w1w_1 is common to a[0..i)a[0..i) and b[0..j)b[0..j), and w2w_2 to a[i..n)a[i..n) and b[j..m)b[j..m):

jj0123456
F[j]F[j]: CAR vs b[0..j)b[0..j)0111111
B[j]B[j]: TOON vs b[j..6)b[j..6)3332210
F[j]+B[j]F[j] + B[j]3443321
aa = CARTOON split after CAR, against bb = ACTION. The maximum, 4, is the LCS length. The first maximizing column, j=1j = 1, splits ACTION into A and CTION, and the recursion returns A + TON = ATON; j=2j = 2 works too.
python
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'))      # ATON

Checked 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 O(n+m)O(n + m).)

DerivationTime and space
  1. T(n,m) ≤ c nm+T(n2, j)+T(n2, m−j)T(n, m)\ \le\ c\,nm + T\big(\tfrac n2,\ j\big) + T\big(\tfrac n2,\ m - j\big)

    A call on an n×mn \times m problem runs two row passes over about n2×m\tfrac n2 \times m cells each: at most c nmc\,nm time for a constant cc. Its two subproblems are n2×j\tfrac n2 \times j and n2×(m−j)\tfrac n2 \times (m - j), whose areas add up to half of the parent's:

  2. T(n,m) ≤ c nm+c nm=2c nmT(n, m)\ \le\ c\,nm + c\,nm = 2c\,nm

    Guess T(n,m)≤2c nmT(n, m) \le 2c\,nm and substitute: the children contribute at most 2c⋅n2 (j+m−j)=c nm2c \cdot \tfrac n2\,(j + m - j) = c\,nm, so the guess reproduces itself. The work per level halves, a geometric series, so there is no factor of log⁡n\log n:

  3. S(n,m)=O(n+m)S(n, m) = O(n + m)

    Space: two rows of length m+1m + 1 at a time, a recursion stack of depth O(log⁡n)O(\log n), 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 kk-th row; during the traceback, recompute one block of kk rows at a time from its checkpoint. The forward pass costs nmnm, the recomputation another nmnm, and memory is (n/k+k) m(n/k + k)\,m values, smallest at k=nk = \sqrt n:

time≤2nm,space=O(mn).\text{time} \le 2nm, \qquad \text{space} = O(m\sqrt n).

Applying the idea recursively inside the blocks, with LL levels, gives space O(L n1/Lm)O(L\, n^{1/L} m) for time O(L nm)O(L\, nm); with L=log⁡2nL = \log_2 n that is O(mlog⁡n)O(m \log n) space for O(nmlog⁡n)O(nm \log n) 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 O(n+m)O(n + m) 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, LCS(a,b)=max⁡j(F[j]+B[j])\mathrm{LCS}(a, b) = \max_j \big(F[j] + B[j]\big), yields an LCS in O(nm)O(nm) time and O(n+m)O(n + m) space, because the subproblems' areas halve at every level.
  • Checkpointing trades time for space in any DP: 2nm2nm time with O(mn)O(m\sqrt n) space, or O(mlog⁡n)O(m \log n) space with logarithmically many levels, the same idea as gradient checkpointing. General simulations reach space O(tlog⁡t)O(\sqrt{t \log t}) for time tt (Williams, 2025).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

After filling an n×mn \times m LCS table, what does a traceback by recomputation cost?

  1. O(nm)O(nm) more time, since every cell is revisited
  2. O(n+m)O(n + m) time and no memory beyond the table
  3. O(log⁡(nm))O(\log(nm)) time, by binary search
  4. It is impossible without stored parent pointers
Show the answer

B. O(n+m)O(n + m) time and no memory beyond the table

Each step of the walk moves up, left or diagonally, so there are at most n+mn + m steps, and each re-evaluates one cell's options from the table in O(1)O(1). Parent pointers would make each step a lookup but cost memory for every cell.

Question 2

Why does the one-row 0/1 knapsack scan the capacities from WW down to ww?

  1. It is faster than scanning upward
  2. So that best[c−w]\text{best}[c - w] still holds the value without the current item when best[c]\text{best}[c] is updated
  3. So that the items are considered in order of decreasing weight
  4. It does not matter: both directions give the 0/1 answer
Show the answer

B. So that best[c−w]\text{best}[c - w] still holds the value without the current item when best[c]\text{best}[c] is updated

Downward, every cell below cc still belongs to the previous row when best[c]\text{best}[c] is updated, so each item is used at most once. Upward, best[c−w]\text{best}[c - w] may already include the item, which allows unlimited copies: the unbounded knapsack.

Question 3

Hirschberg's algorithm recurses on two subproblems at every level. Why is its total time O(nm)O(nm) rather than O(nmlog⁡n)O(nm \log n)?

  1. Because the recursion depth is constant
  2. Because the two subproblems' areas add up to half of the parent's, so the work per level halves
  3. Because it computes only the LCS length, not the LCS itself
  4. 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 cc times the area it processes. The children have areas n2j\tfrac n2 j and n2(m−j)\tfrac n2 (m - j), together nm2\tfrac{nm}{2}, so the levels cost c nmc\,nm, c nm/2c\,nm/2, c nm/4c\,nm/4, …, which sum to at most 2c nm2c\,nm.

Question 4

In Hirschberg's split, F[j]+B[j]F[j] + B[j] reaches its maximum at two different columns jj. Which may the algorithm use?

  1. Only the smaller one
  2. Only the larger one
  3. Either one: each yields an optimal split
  4. 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 jj, 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.