Sub topic 13
Getting the Answer Back: Reconstruction After Compression
Earlier chapters cut DP memory by keeping only the rows or variables that a transition reads. That works when you only need the optimal value, such as the LCS length or the best knapsack total. Many real tasks also need the solution itself: which items to pack, which characters form the subsequence, which edits turn one string into another. This chapter covers how to get that solution back after compression and what each method costs.
This chapter assumes you know rolling rows, the single-array 0/1 knapsack with its downward loop, and the standard LCS recurrence.
Why Compression Destroys the Path
With a full table, reconstruction is a backward walk. You start at the final cell and ask which transition produced its value. Then you step to that predecessor and repeat. Every cell the walk visits must still exist.
Rolling rows overwrite exactly those cells. After the forward pass, the two-row LCS keeps only rows m-1 and m. The walk from (m, n) soon needs row m-2, and that row is gone. The single-array knapsack is worse. Its final dp array only describes "all items considered", so you cannot tell from it whether item 3 was taken.
Reconstruction always means paying for something. You can pay with memory by keeping more data, or with time by recomputing what you threw away. The methods below sit at different points between those two costs.
Strategy 1: Keep Only the Decisions
The value table holds integers, but the backward walk only needs to know which transition won at each cell. That is a small choice: "take or skip" for knapsack, and "diagonal, up, or left" for LCS. You can roll the value rows as before and store the choices in a compact table on the side.
The decision table is still O(m·n) in size, but its constant factor is much smaller. One byte per cell replaces a 4- or 8-byte integer. Packing 2 bits per cell shrinks it further.
Knapsack with a keep table
def knapsack_with_items(weights, values, capacity):
n = len(weights)
dp = [0] * (capacity + 1)
keep = [bytearray(capacity + 1) for _ in range(n)]
for i, (w, v) in enumerate(zip(weights, values)):
for c in range(capacity, w - 1, -1):
if dp[c - w] + v > dp[c]:
dp[c] = dp[c - w] + v
keep[i][c] = 1
items = []
c = capacity
for i in range(n - 1, -1, -1):
if keep[i][c]:
items.append(i)
c -= weights[i]
items.reverse()
return dp[capacity], items
print(knapsack_with_items([1, 3, 4, 5], [1, 4, 5, 7], 7)) # (9, [1, 2])keep[i][c] = 1 records that the best answer using items 0..i with capacity c includes item i. The backward loop visits items in reverse. It takes an item when its flag is set and then lowers c by that item's weight, which jumps to the state the optimum came from. The value array stays one-dimensional. Only the bit table grows with n.
LCS with a move table
def lcs_string(x, y):
m, n = len(x), len(y)
W = n + 1
move = bytearray((m + 1) * W) # 1 = diagonal, 2 = up, 3 = left
prev = [0] * W
for i in range(1, m + 1):
curr = [0] * W
for j in range(1, n + 1):
if x[i - 1] == y[j - 1]:
curr[j] = prev[j - 1] + 1
move[i * W + j] = 1
elif prev[j] >= curr[j - 1]:
curr[j] = prev[j]
move[i * W + j] = 2
else:
curr[j] = curr[j - 1]
move[i * W + j] = 3
prev = curr
out = []
i, j = m, n
while i > 0 and j > 0:
d = move[i * W + j]
if d == 1:
out.append(x[i - 1])
i -= 1
j -= 1
elif d == 2:
i -= 1
else:
j -= 1
return ''.join(reversed(out))
print(lcs_string("ABCBDAB", "BDCABA")) # BCBAA flat bytearray avoids the overhead of Python's per-object list storage. When there is a tie, the tie-break (>= prefers "up") decides which of several optimal answers you get. Keep the tie-break the same everywhere you reconstruct, or two runs can return different but equally valid strings.
Strategy 2: Checkpoint Rows and Recompute
If even a byte per cell is too much, store whole value rows only at intervals. Save every k-th row during the forward pass. During the backward walk, when you need rows inside a block, rebuild that block from the checkpoint below it. Each block is rebuilt once, so the total extra work is about one more forward pass.
With k ≈ √m, you hold about √m checkpoint rows plus a block of up to k+1 rows. Space drops to O(√m · n), and time roughly doubles.
import math
def lcs_checkpointed(x, y):
m, n = len(x), len(y)
k = max(1, math.isqrt(m))
def next_row(prev, ch):
curr = [0] * (n + 1)
for j in range(1, n + 1):
if ch == y[j - 1]:
curr[j] = prev[j - 1] + 1
else:
curr[j] = max(prev[j], curr[j - 1])
return curr
checkpoints = {0: [0] * (n + 1)}
row = checkpoints[0]
for i in range(1, m + 1):
row = next_row(row, x[i - 1])
if i % k == 0:
checkpoints[i] = row
out = []
i, j = m, n
while i > 0 and j > 0:
base = (i - 1) // k * k
block = [checkpoints[base]]
for r in range(base + 1, i + 1):
block.append(next_row(block[-1], x[r - 1]))
while i > base and j > 0:
cur = block[i - base]
up = block[i - base - 1]
if x[i - 1] == y[j - 1]:
out.append(x[i - 1])
i -= 1
j -= 1
elif up[j] >= cur[j - 1]:
i -= 1
else:
j -= 1
return ''.join(reversed(out))
print(lcs_checkpointed("ABCBDAB", "BDCABA")) # BCBAbase is the largest multiple of k that is at most i - 1. That row is always saved, and the block covers every row from base to i. The walk therefore always has both the current row and the row above it. It uses the same tie-break as lcs_string, so the two functions return the same string.
Strategy 3: Divide and Conquer
You can go further and keep only O(n) memory with full reconstruction. To do that, find one cell the optimal path passes through in the middle row, then solve the two halves recursively. That is Hirschberg's algorithm, the topic of the next chapter. It costs about twice the time of the value-only pass, and its memory does not grow with m.
When Reconstruction Is Free
Some compressions lose nothing that the walk needs:
- 1D tables you never rolled. In coin change with the fewest coins,
dpis already O(amount). Storelast_coin[a]next to it and follow it backward fromamountto 0. - Rolling variables over a chain. In the cooldown stock problem, the optimal action sequence needs one decision per day per state. A per-day record of which branch won is O(days) bits, which is small compared with the input.
- The answer is a single index. If the DP only picks where something ends, as in maximum subarray, track the best index as you go.
Comparing the Strategies
The figures in the table assume an LCS of two strings of length 10,000, which gives 10⁸ cells and 4-byte integers.
| Strategy | Extra space | Approx. memory | Time vs. value-only | Fits when |
|---|---|---|---|---|
| Full value table | O(mn) ints | 400 MB | 1× | Small inputs, simplest code |
| Rolled values + byte decisions | O(mn) bytes | 100 MB | ~1× | Memory is tight but O(mn) still fits |
| Rolled values + 2-bit packed decisions | O(mn) bits | 25 MB | ~1.1× | Decisions have few options |
| Checkpoints every √m rows | O(√m · n) | ~8 MB | ~2× | Any layered DP, moderate code |
| Hirschberg | O(m + n) | < 1 MB | ~2× | Very large inputs; split point must be findable |
Common Mistakes
- Backtracking against the final compressed array. As the warning above explains, it gives wrong answers without any error. Use stored decisions or rebuilt rows.
- Inconsistent tie-breaking. If the forward pass and the backward walk use different tie rules, the walk can step into a cell that is not on any optimal path. The output may then be shorter than the optimal value.
- Aliasing checkpoint rows. If
next_rowchanged a list in place instead of returning a new one, every checkpoint would point to the same final row. - Storing decisions for skipped cells. In the knapsack keep table, cells with
c < ware never written and stay 0, which correctly means "skip". If you initialize to anything else, the walk breaks.
Exercise
In knapsack_with_items, the strict comparison dp[c - w] + v > dp[c] decides when to set the keep flag. What changes if you replace it with >=, and is the result still correct?
Show answer
Ties now count as "take", so when taking and skipping give the same value, the item is recorded as taken. The total value stays optimal and the item set is still valid, because each flag marks a transition that really reaches dp[c]. You may simply get a different optimal set, one that prefers later items.
Exercise
A DP has 50,000 layers of 20,000 cells each, and each layer depends only on the one before it. You need the solution and have about 200 MB. Decisions need 2 bits per cell. Which strategy fits, and roughly how much memory does it use?
Show answer
The packed decisions take 50,000 × 20,000 × 2 bits = 250 MB, which does not fit. Checkpointing with k ≈ √50,000 ≈ 224 stores about 224 checkpoint rows plus a block of about 225 rows. That is about 449 rows × 20,000 cells × 4 bytes ≈ 36 MB, which fits, at about twice the time. Hirschberg would also work if the problem has a way to split at a middle layer.
Exercise
Why does lcs_checkpointed rebuild each block only once in total, even though the backward walk can move left many times in a row?
Show answer
Moving left changes only j, and the block already holds every row from base to i. The inner loop runs until i drops to base, and only then does the outer loop rebuild the next block down. Each block is entered once, so all the rebuilds together add up to about m rows.