Sub topic 15
Choosing the Right Reduction for a Recurrence
This chapter pulls the earlier techniques together into one decision process. It assumes you have worked through the previous chapters. You should be able to read a recurrence's dependency pattern, and you should know rolling variables, two-row and single-row arrays, loop direction, the saved diagonal, modulo indexing, dimension removal, state machines, bitmasks, sparse maps, memoization costs, and reconstruction with Hirschberg's method. No new technique appears here. The goal is to pick the right technique quickly, justify the choice, and avoid the usual mistakes.
Start with a Correct Baseline
Every reduction rewrites a table you already understand. If you compress a recurrence before you have a correct full-table version, you cannot tell a recurrence bug from a compression bug. A reliable workflow has four steps:
- Write the full-table, bottom-up version and test it.
- Draw the dependency pattern: for each cell, which cells does it read?
- Choose the reduction that the pattern allows and the requirements permit.
- Test the compressed version against the baseline on many random inputs.
Step 4 matters most. Compression bugs often show up only on edge cases, such as a single row, a single column, or an item heavier than the capacity. Hand-picked tests miss these cases. Random comparison catches them.
The Questions to Ask, in Order
The order of the questions matters. Some answers rule out techniques before you look at the dependency pattern at all.
- Does the full table fit comfortably in memory? If 10^6 integers are enough, a full table costs a few megabytes. Keeping the table is often the right call, because it keeps the code simple and the solution easy to reconstruct.
- Do you need the solution itself, or only its value? If you need the solution, plain rolling arrays are not enough by themselves. You will need to keep the table, store compact decision bits, or use Hirschberg's method.
- Is the solution top-down? Memoization keeps every visited state plus a recursion stack. Convert to bottom-up first, because rolling techniques need a fixed evaluation order.
- Can any state dimension be derived from the others? Remove it before you look at the dependency pattern, since this shrinks the table by a whole factor.
- What does each transition read? This answer picks the layout: rolling variables, modulo buffer, two rows, single array, or single array with a saved diagonal.
- Is the state space mostly unreachable, or is it a set of chosen items? Use a hash map for sparse states and a bitmask for subset states.
Comparing the Techniques
The table below summarizes what each technique needs, what it saves, and what it costs. Here n is the length of the sequence and m by n is the size of the original 2D table.
| Technique | Fits when | Space after | Reconstruction | Main risk |
|---|---|---|---|---|
| Rolling variables | 1D, reads a fixed few earlier values | O(1) | Lost unless choices are logged | Updating variables in the wrong order |
| Modulo buffer | 1D, reads the last k values | O(k) | Lost | Off-by-one in the index or the base cases |
| Two rows | 2D, row i reads only row i-1 | O(min(m, n)) | Lost; Hirschberg recovers it | Forgetting to reset the current row |
| Single array, chosen direction | Row i reads row i-1 and row i | O(n) | Lost | Wrong loop direction silently changes the problem |
| Single array plus diagonal | Also reads (i-1, j-1) | O(n) | Lost | Saving the diagonal at the wrong moment |
| Drop a derivable dimension | One coordinate is a function of others | Divides by that dimension | Usually kept | Choosing an evaluation order that breaks the derivation |
| State machine | Few modes per step | O(number of modes) | Lost unless logged | Using an updated value in the same step |
| Bitmask | State is a subset of up to about 20 items | O(2^n) entries | Kept if the table is kept | Exponential growth past small n |
| Hash map of states | Most states are unreachable | O(reachable states) | Kept if parents are stored | Per-entry overhead of 50 to 100 bytes in Python |
| Hirschberg | 2D alignment, solution required | O(min(m, n)) | Full | About twice the time and more complex code |
Trade-offs Beyond Space
Saving memory is rarely free. Weigh these costs before committing to a technique.
- Reconstruction. Every rolling technique throws away the information you would trace back through. If the solution is needed later, plan for it at the start. Choosing a technique and then bolting on reconstruction usually means rewriting it.
- Time. Most rolling techniques keep the same asymptotic time and often run faster, because a small array stays in the CPU cache. Hirschberg roughly doubles the work. Hash maps add hashing cost to every lookup.
- Clarity.
dp[i][j]says what it means. A single array with a saved diagonal does not. Add a comment that states the invariant, for example "before the update,dp[j]holds row i-1." - Constant factors in Python. A list of 10^7 Python ints costs about 80 MB for pointers alone. The
arraymodule or NumPy stores the same values in a quarter of that space. Sometimes this change is enough, and no change to the recurrence is needed. - Recursion limits. Top-down memoization on a chain of 10^5 states fails with Python's default recursion limit of 1000 before memory becomes a problem.
Worked Example: Minimum Path Sum
Problem: in a grid of non-negative costs, move only right or down from the top-left cell to the bottom-right cell, and minimize the total cost. Only the minimum value is required.
Apply the questions. The output is a single number, so no reconstruction is needed. The recurrence is bottom-up. No dimension is derivable. Each cell reads the cell above, (i-1, j), and the cell to the left, (i, j-1). That is the previous row plus the current row, with no diagonal. The flowchart points to a single array updated left to right. Before the update, dp[j] still holds the value from above. dp[j-1] has already been updated, so it holds the value to the left. Space drops from O(mn) to O(n).
The code below contains the baseline, the compressed version, and a random comparison test.
import random
def min_path_full(grid):
m, n = len(grid), len(grid[0])
dp = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i == 0 and j == 0:
dp[i][j] = grid[0][0]
elif i == 0:
dp[i][j] = dp[i][j - 1] + grid[i][j]
elif j == 0:
dp[i][j] = dp[i - 1][j] + grid[i][j]
else:
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j]
return dp[m - 1][n - 1]
def min_path_row(grid):
n = len(grid[0])
# Invariant: before updating dp[j], it holds the value from the row above.
dp = [float('inf')] * n
dp[0] = 0
for row in grid:
dp[0] += row[0]
for j in range(1, n):
dp[j] = min(dp[j], dp[j - 1]) + row[j]
return dp[-1]
random.seed(1)
for _ in range(2000):
m, n = random.randint(1, 6), random.randint(1, 6)
grid = [[random.randint(0, 9) for _ in range(n)] for _ in range(m)]
assert min_path_full(grid) == min_path_row(grid), grid
print("all trials passed")Filling the array with infinity handles the first row without a special case. On the first pass, dp[j] is infinite, so the minimum always picks the left neighbor. The random sizes include 1 by 1 grids, single rows, and single columns. Those are exactly the shapes where a hand-compressed version tends to break.
If the problem also asked for the path itself, the second question would change the answer. For a grid of a few million cells, one direction bit per cell costs well under a megabyte, and you can trace the path back from the bottom-right corner. Only when even that is too large would you switch to a divide-and-conquer approach like Hirschberg's.
Common Errors When Choosing
- Compressing a table that fits. A 1000 by 1000 table of ints is fine. Compressing it adds bugs and removes reconstruction for no practical gain.
- Reading the pattern from memory instead of the recurrence. Two recurrences that look alike, such as LCS and edit distance, differ in whether the diagonal must be saved. Write out the cells each transition reads.
- Choosing the loop direction by habit. Downward iteration fits "each item at most once," and upward iteration fits "unlimited reuse." Derive the direction from whether the read cell should hold the old value or the new one.
- Compressing memoization directly. Convert to bottom-up first. A memo dictionary has no evaluation order you can roll over.
- Forgetting the answer's location. After compression, the answer is in
dp[-1],prev[n], ort[n % k], notdp[m][n]. Off-by-one returns are common.
Exercise
A recurrence over a string of length n has states dp[i][j] for 0 <= i <= j < n, where dp[i][j] reads dp[i+1][j-1], dp[i+1][j], and dp[i][j-1]. Only the value is needed, and n is 20000. Which reduction fits, in what order should you iterate, and what space results?
Show answer
The full table has about 2 * 10^8 cells, which is too large. Each cell reads row i+1 and the current row i, including the diagonal dp[i+1][j-1]. Iterate i from n-1 down to 0 and j upward from i+1. Use a single array indexed by j, plus a saved-diagonal temporary that holds the old dp[j-1] (row i+1) before it is overwritten. Space drops to O(n), about 20000 entries.
Exercise
You must report which items a 0/1 knapsack picks. There are 500 items, and the capacity is 100000. The full value table holds 5 * 10^7 Python ints. Propose a lower-memory approach and give its approximate size.
Show answer
Keep the single-array value computation, iterated downward, and also record one "took item" bit per (item, capacity) pair, for example in a bytearray used as a bitset. That is 5 * 10^7 bits, about 6 MB, instead of hundreds of megabytes of int pointers. To reconstruct, walk the items backward from the full capacity. When an item's bit is set at the current capacity, subtract its weight.
Exercise
A colleague replaced a working top-down memoized solution with rolling variables, and the results are now wrong on some inputs. What two steps should they have taken first?
Show answer
First, convert the memoized version to a bottom-up table with an explicit evaluation order, and confirm that it matches. Second, write out the cells each transition reads in that order, and only then pick a rolling layout. Test the result against the bottom-up baseline on random inputs.