Sub topic 11
Storing Only Reachable States
This chapter assumes you know bottom-up tabulation and the 0/1 knapsack recurrence. It also assumes you know how Python dictionaries behave, including that you cannot add keys to a dictionary while you loop over it.
The Problem with Dense Tables
A dense table has a slot for every possible state, even the ones no input can ever produce. The single-array knapsack uses capacity + 1 slots. With a capacity of 8,000,000 and three items, that is eight million integers. Yet three items can produce at most 2³ = 8 distinct total weights. Almost every slot stays at its initial value and is never useful.
When reachable states are rare compared with possible states, store only the states you actually reach. A hash map does this: the key is the state and the value is the best result for that state.
Sparse 0/1 Knapsack
The map best takes a total weight to the highest value that reaches exactly that weight. Each item extends every state that already exists.
def knapsack_sparse(weights, values, capacity):
best = {0: 0} # total weight -> best value at that weight
for w, v in zip(weights, values):
new = dict(best) # option 1: skip this item
for used, val in best.items(): # option 2: take it
nw = used + w
if nw <= capacity and val + v > new.get(nw, -1):
new[nw] = val + v
best = new
return max(best.values())
print(knapsack_sparse([3_000_000, 5_000_000, 4_000_000], [40, 70, 50], 8_000_000))
# 110The code reads from best and writes to new. This does the same job as the downward loop in the dense version. Each item extends only the states from the previous layer, so no item is used twice.
How Much Memory It Saves
The map holds at most min(capacity + 1, 2ⁿ) entries. Time is O(n × number of states) instead of O(n × capacity).
Hash maps cost more per entry than arrays. In CPython, a dictionary entry plus its integer objects uses roughly 100 bytes. A slot in a compact array uses about 8 bytes. Sparse storage pays off only when the fraction of reachable states is small.
| Situation | Better choice |
|---|---|
| Capacity small, many items | Dense array |
| Capacity huge, few items | Hash map |
| Weights share a large common factor | Divide by the factor, then use a dense array |
| Reachable states over ~10% of the range | Dense array |
You can shrink the map further with dominance pruning. Suppose one state is lighter than another and also has at least the same value. Then the heavier state can never lead to a better answer, so you can drop it. After that pruning, the surviving states have values that rise as weight rises.
Common Errors
- Mutating the map while iterating it. Writing
best[nw] = ...insidefor used in bestraisesRuntimeError: dictionary changed size during iteration. If you loop over a snapshot copy instead, the error goes away, but an item can then be reused within its own layer. - Forgetting to prune. If you leave out the
nw <= capacitycheck, out-of-range states fill the map. For large n they can grow it toward 2ⁿ entries. - Assuming sparse is always smaller. Count the states you expect to reach before you switch. Dense storage often wins on small ranges.
- Using
maxon an empty map. Seeding the map with{0: 0}guarantees at least one entry.
Exercise
You need to know whether some subset of 20 integers, each up to 10^9, sums to exactly T. Should you use a dense boolean array or a set of reachable sums, and what is the worst-case number of stored states?
Show answer
Use a set of reachable sums. A dense array would need up to T + 1 slots, possibly around 2 × 10^10, while 20 items can produce at most 2^20 ≈ 1,048,576 distinct sums. Discard sums greater than T as you go to keep the set smaller.
Exercise
Why does the sparse knapsack copy best into new instead of updating best directly inside the loop?
Show answer
Reading from the previous layer (best) and writing to the next (new) ensures each extension uses only states that existed before the current item, so the item is counted at most once. Direct updates would also fail with a RuntimeError because the dictionary would change size during iteration.