Sub topic 13
Getting the Answer Back: Reconstruction After Compression
This chapter assumes you know the rolling-row and single-array techniques from earlier chapters, and that you can backtrack through a full DP table to recover an optimal solution.
What Compression Throws Away
A full DP table stores the optimal value and the history of how each value was reached. To reconstruct a solution, you start at the final cell and ask which transition produced it. Then you step to that predecessor and repeat until you reach a base case.
Rolling rows and single arrays overwrite that history. After the 0/1 knapsack loop finishes, dp[capacity] holds the best value, but nothing records which items produced it. The array only tells you the value.
You have four ways to get the solution back.
Storing Decisions Instead of Values
Backtracking needs the choice made at each cell. It does not need the value. A choice usually fits in one bit or a small integer, which is far cheaper than a stored value. In Python, an int in a list costs an 8-byte pointer plus a 28-byte object, while a bytearray cell costs 1 byte.
For 0/1 knapsack, keep the single value array and add a take flag per item and capacity:
def knapsack_with_items(weights, values, capacity):
dp = [0] * (capacity + 1)
take = [bytearray(capacity + 1) for _ in weights]
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
take[i][c] = 1
items = []
c = capacity
for i in range(len(weights) - 1, -1, -1):
if take[i][c]:
items.append(i)
c -= weights[i]
return dp[capacity], items[::-1]
print(knapsack_with_items([1, 3, 4], [15, 20, 30], 4)) # (35, [0, 1])take[i][c] == 1 means that, after considering items 0..i, the best value at capacity c used item i. The backtrack walks the items in reverse. When the flag is set, it records the item and moves to the reduced capacity. Otherwise the value at c was inherited from the previous item, and c stays the same.
The space is still O(n · W). The improvement is in the constant factor. Packing eight flags into each byte with bit operations shrinks it by another 8x.
Comparing the Options
| Approach | Extra space | Extra time | Notes |
|---|---|---|---|
| Full value table | O(n · W) values | none | Simplest. Often too large |
| Decision bits | O(n · W) bits | none | Smaller constant. Same O-class |
| Recompute on demand | O(W) plus checkpoints | up to O(n) recomputations | Store every √n-th row and rebuild the rows between checkpoints when backtracking |
| Hirschberg | O(min(m, n)) | about 2x | Works for LCS and edit-distance style grids (next chapter) |
Common Errors
- Reading decisions from the wrong layer. In a single-array update,
dp[c - w]refers to the previous item only if the loop runs downward. The decision flags inherit that requirement. - Backtracking through
dpalone. A compresseddpholds only final-layer values, so comparingdp[c]todp[c - w] + vduring the backtrack uses the wrong values. - Forgetting the base case. The walk must stop at item index −1 or at capacity 0, not at the first cell with a zero flag.
Exercise
You compress LCS to two rows and store a 2-bit direction code (diagonal, up, left) per cell for reconstruction. For strings of length 10,000 and 10,000, how much memory do the direction codes take, and does this beat a full table of 4-byte integers?
Show answer
10,000 × 10,000 = 10^8 cells × 2 bits = 2 × 10^8 bits = 25 MB. A full 4-byte integer table takes 400 MB, so direction codes are 16x smaller. Both are still O(mn), so Hirschberg's algorithm is needed to reach linear space.
Exercise
In knapsackwithitems, why does the backtrack loop run from the last item to the first?
Show answer
Each flag take[i][c] describes the best solution over items 0..i at capacity c. Only the last item's flags describe the final answer at the full capacity. Each step then reduces the problem to items 0..i-1 at the updated capacity.