Sub topic 11
Storing Only Reachable States
The earlier chapters shrank DP tables by throwing away layers that no later transition reads. This chapter targets a different waste. Many dense tables are mostly empty, because most indices never correspond to any state the recurrence can actually produce. If you store only the states that are reachable from the base case, memory scales with the number of real states instead of the size of the index range.
This chapter assumes you are comfortable with bottom-up tabulation, the two-row rolling technique, and Python dictionaries, including the fact that a dictionary lookup takes O(1) expected time.
When a Dense Table Is Mostly Empty
Take a 0/1 knapsack where the capacity is 10^9 and there are 30 items. The single-array solution from the loop-direction chapter allocates capacity + 1 slots. That comes to a billion entries, and it is infeasible no matter how cleverly you iterate. Yet after processing k items, at most 2^k distinct total weights exist, and in practice far fewer fit under the capacity or survive pruning. Almost every slot in the dense array would hold the default value forever.
The same pattern shows up wherever the index is a value (a sum, a weight, a coordinate) and not a count:
- Subset sums or knapsack with large weights and few items.
- Sign-assignment problems, where sums range over [-S, S] but only some values occur.
- Grid or graph searches where obstacles or rules make most cells unreachable.
- Subset states (bitmasks) where constraints rule out most masks.
The fix keeps the recurrence unchanged and swaps the storage: a hash map from state key to value, holding only the keys that have been reached.
Sparse 0/1 Knapsack
The dense version indexes by capacity. The sparse version maps each reachable total weight to the best value seen for it. Each item produces a new layer built from the old one. This is the rolling-rows idea carried over to dictionaries.
def knapsack_sparse(weights, values, capacity):
best = {0: 0} # total weight -> best value at that weight
for w, v in zip(weights, values):
nxt = dict(best) # option: skip this item
for tw, tv in best.items():
nw = tw + w
if nw <= capacity and nxt.get(nw, -1) < tv + v:
nxt[nw] = tv + v # option: take this item
best = nxt
return max(best.values())
weights = [10**9 // 3, 10**9 // 2, 10**9 // 4, 7]
values = [60, 100, 40, 1]
print(knapsack_sparse(weights, values, 10**9)) # 161With four items the map never holds more than 16 entries, even though the capacity is a billion.
Building nxt from best, instead of writing into best directly, is what enforces the at-most-once rule. Every read comes from the previous layer. This plays the same role as iterating capacity downward in the dense array.
Pruning Dominated States
Reachable states can still blow up. After n items the map may hold up to 2^n weights. Many of them are useless. If one state has weight 50 and value 80, and another has weight 60 and value 70, the second one is dominated: it weighs more and is worth less. No completion of it can beat the same completion of the first.
Dropping dominated states after each layer keeps only the Pareto frontier, where value strictly increases with weight.
def prune(states):
kept = {}
top = -1
for w in sorted(states):
v = states[w]
if v > top:
kept[w] = v
top = v
return kept
def knapsack_sparse_pruned(weights, values, capacity):
best = {0: 0}
for w, v in zip(weights, values):
nxt = dict(best)
for tw, tv in best.items():
nw = tw + w
if nw <= capacity and nxt.get(nw, -1) < tv + v:
nxt[nw] = tv + v
best = prune(nxt)
return max(best.values())
print(knapsack_sparse_pruned([10**9 // 3, 10**9 // 2, 10**9 // 4, 7],
[60, 100, 40, 1], 10**9)) # 161Sorting costs O(m log m) per layer for a map of size m. That is usually a good trade, because pruning often shrinks the map by orders of magnitude. After pruning, the maximum value is simply the value at the largest kept weight. You could read it directly instead of calling max.
Pruning depends on the problem. It is valid here because the objective is monotone: more value is always better, and less weight never hurts. In a counting problem you cannot drop any state, because every path contributes to the count.
Sparse Counting: Assigning Signs
Count the ways to put + or - in front of each number so the total equals target. A dense solution needs an offset array of size 2S + 1, where S is the sum of absolute values. A sparse map stores only the sums that actually occur.
from collections import defaultdict
def sign_ways(nums, target):
ways = {0: 1} # running sum -> number of sign assignments reaching it
for x in nums:
nxt = defaultdict(int)
for s, c in ways.items():
nxt[s + x] += c
nxt[s - x] += c
ways = nxt
return ways.get(target, 0)
print(sign_ways([1, 1, 1, 1, 1], 3)) # 5
print(sign_ways([10**12, 10**12, 3], 3)) # 2The second call would need an array of about 4 × 10^12 entries in dense form. The sparse map never holds more than four keys at once.
Use ways.get(target, 0) to read the answer, not ways[target]. A defaultdict silently inserts missing keys when you index it. That is harmless at the end, but inside a loop it can add phantom states that later iterations treat as real.
Choosing Keys
A state key must be hashable and must identify the state exactly.
| State shape | Good key | Avoid |
|---|---|---|
| Single integer (sum, weight) | `int` | `str(n)`: slower, larger |
| Several integers | `tuple` such as `(i, w)` | lists, which are unhashable |
| Small subset | bitmask `int` | `frozenset`: works, but heavier |
| Integers with known bounds | packed `int`, e.g. `i * W + w` | floats, which risk rounding collisions |
Packing a tuple into a single integer saves the tuple object for each entry. It only works when the bounds are known and the packed values cannot collide.
The Cost Per Entry
Sparse storage is not free. A Python list of small integers costs about 8 bytes per slot for the pointer. A dictionary entry costs several times that once you count the hash table slot, the key object, the value object, and the table's spare capacity. Expect a rough factor of 5 to 15 over a compact array. Lookups also hash the key and follow pointers, so each one runs slower than an array index.
| Property | Dense array | Hash map of reachable states |
|---|---|---|
| Memory | Proportional to index range | Proportional to reachable states, times overhead |
| Access | Direct index, cache-friendly | Hash and probe, less cache-friendly |
| Unreachable states | Stored anyway | Never stored |
| Iteration order | Natural index order | Insertion order; sort if order matters |
| Best when | Most indices are reached | A small fraction of indices is reached |
A practical rule: estimate the reachable count R and the index range N. If R is above about a tenth of N, a dense array, possibly rolled, is usually smaller and faster. If R is a tiny fraction of N, or N is too large to allocate at all, use the map.
Edge Cases and Failure Modes
- No reachable-state savings in the worst case. With weights 1, 2, 4, 8, ..., every subset gives a distinct sum, so the map grows to 2^n. Sparsity helps only when the structure of the problem limits the states or pruning cuts them.
- Dense inputs. With 1000 items of weight 1 to 10 and capacity 5000, nearly every weight from 0 to 5000 becomes reachable. The map then wastes memory compared with a 5001-slot array.
- Forgetting to bound. Without the
nw <= capacitycheck, the map fills with states that can never be part of an answer. - Mixing layers. Writing into the map you are reading from breaks 0/1 semantics, just as an upward loop does in the dense knapsack.
- Reconstruction. Keeping only the current map loses the history, the same as with rolling rows. A later chapter covers how to recover the chosen items.
Top-down memoization also stores only the states it visits, so it is sparse automatically. Its memory costs come from different sources, which the next chapter examines.
Exercise
You need the number of distinct subset sums of 40 integers, each between 1 and 10^15. Would you use a dense boolean array or a set of reachable sums, and what is the worst-case size of your structure?
Show answer
Use a set of reachable sums. A dense array would need about 4 × 10^16 entries, which cannot be allocated. The set holds at most 2^40 sums in the worst case, so for adversarial inputs a meet-in-the-middle approach may also be needed. Typical inputs with repeated or structured values stay much smaller.
Exercise
In knapsack_sparse, why is it wrong to replace nxt = dict(best) and the loop over best.items() with direct writes into best while iterating over list(best.items())? Is it actually wrong?
Show answer
It is not wrong. The snapshot list(best.items()) freezes the previous layer, so every read comes from it, and writes to best cannot feed back into the same item's updates. Each item is still used at most once. The only requirement is that reads come from the snapshot and not from the live map.
Exercise
Why can you apply dominance pruning to the knapsack map but not to the sign_ways map?
Show answer
Knapsack maximizes value, so a state with higher weight and lower value can never lead to a better final answer than the state that dominates it. sign_ways counts every assignment, so each state's count contributes to the total and none can be discarded without changing the answer.