Sub topic 5
One Array, Updated in Place: Why Loop Direction Matters
The previous chapter cut a 2D table down to two rows: one for the previous layer and one for the current layer. This chapter goes one step further and keeps a single array. The new problem is that old and new values now share the same cells. Whether a read returns the old value or the new one depends only on the order you visit the cells. If you choose the wrong order, the code still runs and returns plausible numbers, but they are wrong.
This chapter assumes you know bottom-up tabulation, the 0/1 knapsack recurrence, and the dependency-arrow reading of a recurrence from the earlier chapters.
The Two-Row Version as a Starting Point
The 0/1 knapsack recurrence, with dp[i][c] meaning the best value using the first i items with capacity c, is:
dp[i][c] = max(dp[i-1][c], dp[i-1][c - w_i] + v_i)whenc >= w_idp[i][c] = dp[i-1][c]otherwise
Both reads come from row i-1. One is directly above the cell, and the other is above and to the left. Nothing in row i is read. With two rows the code would look like this:
def knapsack_two_rows(weights, values, capacity):
prev = [0] * (capacity + 1)
for w, v in zip(weights, values):
curr = prev[:]
for c in range(w, capacity + 1):
curr[c] = max(prev[c], prev[c - w] + v)
prev = curr
return prev[capacity]To drop curr, the code must write into prev directly. Each write then destroys a row i-1 value. The question is whether any later read in the same pass still needs that value.
Why Downward Iteration Is Correct for 0/1 Knapsack
Cell c reads cell c and cell c - w, and c - w never has a larger index than c. Suppose you sweep capacities from high to low. When you write cell c, every cell below c has not been touched yet in this pass, so dp[c - w] still holds the row i-1 value. Cell c itself is read before it is overwritten. Every read sees the old row, which is what the recurrence requires.
def knapsack_01(weights, values, capacity):
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]Space drops from O(n · C) to O(C). The time is unchanged at O(n · C).
What Goes Wrong in the Upward Direction
Sweep upward instead and cell c - w is written before cell c. The read of dp[c - w] then sees the current item's value, so the item can be counted again. Take one item with weight 2 and value 3, and capacity 4:
| Direction | Order of writes | dp[2] | dp[3] | dp[4] | Result |
|---|---|---|---|---|---|
| Downward | 4, 3, 2 | 3 | 3 | 3 | 3 (item used once) |
| Upward | 2, 3, 4 | 3 | 3 | 6 | 6 (item used twice) |
In the upward sweep, dp[4] = dp[2] + 3, and dp[2] already includes the item. The bug produces no error. It answers a different problem: knapsack where each item can be reused.
def knapsack_wrong_direction(weights, values, capacity):
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for c in range(w, capacity + 1): # upward: BUG for 0/1
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
print(knapsack_01([2], [3], 4)) # 3
print(knapsack_wrong_direction([2], [3], 4)) # 6Upward Iteration as a Feature: Unbounded Problems
The upward "bug" is exactly what unbounded problems need. In unbounded knapsack the recurrence reads the current row on purpose: dp[i][c] = max(dp[i-1][c], dp[i][c - w_i] + v_i). The second term means "take item i and stay on row i, so it can be taken again." An upward sweep makes dp[c - w] hold the row i value when cell c reads it.
Counting coin combinations has the same structure:
def coin_change_ways(coins, amount):
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for a in range(coin, amount + 1):
dp[a] += dp[a - coin]
return dp[amount]
print(coin_change_ways([1, 2, 5], 5)) # 4The += reads the old dp[a], which is the count without this coin (row i-1). It adds dp[a - coin], which already includes this coin (row i). The 2D recurrence ways[i][a] = ways[i-1][a] + ways[i][a - coin] turns into one line because the update order lines each read up with the right layer.
The General Rule
Work out, for each read, which layer it needs and whether its index comes before or after the cell being written in the sweep:
| Read needs | Read index is earlier in sweep | Read index is later in sweep |
|---|---|---|
| Previous layer (old value) | Unsafe: already overwritten | Safe |
| Current layer (new value) | Safe | Unsafe: not yet written |
For a 1D array, "earlier in sweep" means smaller index when sweeping upward and larger index when sweeping downward. 0/1 knapsack reads a smaller index from the old layer, so it sweeps downward. Unbounded knapsack reads a smaller index from the new layer, so it sweeps upward.
If one cell needs an old value on one side and a new value on the same side, no single direction works. The same is true if it needs old values on both sides of itself. You then need two rows, or the saved-value trick from the next chapter.
Edge Cases Worth Knowing
Loop nesting changes the question too
In coin_change_ways, the coin loop sits outside the amount loop. Each coin is fully processed before the next one starts, so every combination is counted once, in a fixed coin order. If you swap the loops, the same array counts ordered sequences (permutations) instead:
def coin_sequences(coins, amount):
dp = [0] * (amount + 1)
dp[0] = 1
for a in range(1, amount + 1):
for coin in coins:
if coin <= a:
dp[a] += dp[a - coin]
return dp[amount]
print(coin_change_ways([1, 2], 3)) # 2: {1,1,1}, {1,2}
print(coin_sequences([1, 2], 3)) # 3: 1+1+1, 1+2, 2+1The array is the same size in both versions. The meaning of a cell changed, because the array no longer has a per-coin layer.
Zero-weight items
If an item has w = 0, the downward loop includes c - w = c, and dp[c] = max(dp[c], dp[c] + v) reads the cell it is about to write. Python evaluates the right-hand side first, so the item is added once per cell, which is correct for 0/1. The unbounded version is undefined in principle, because a zero-weight item with positive value can be taken forever. Filter such items out or handle them separately.
Bounded multiplicity
If item i can be used up to k times, neither direction alone is correct. A common fix splits the item into copies of size 1, 2, 4, …, followed by a remainder. Each copy is then processed as a 0/1 item with a downward sweep. Memory stays O(C), and time becomes O(C · Σ log k_i).
Losing the per-item rows
A single array keeps only the final layer. You can no longer trace back through earlier rows to find which items were chosen. A later chapter covers how to recover the solution.
Exercise
Write a single-array function count_subsets(nums, target) that returns how many subsets of nums (each element used at most once, all elements positive) sum to target. Which loop direction do you need, and why?
Show answer
Use a downward sweep, because each element may be used once, so dp[s - x] must still hold the count from before x was considered. def countsubsets(nums, target): dp = [0] * (target + 1) dp[0] = 1 for x in nums: for s in range(target, x - 1, -1): dp[s] += dp[s - x] return dp[target] For example, countsubsets([1, 2, 3], 3) returns 2 ({3} and {1, 2}).
Exercise
A recurrence over one array has dpnew[j] = dpold[j] + dp_old[j + 1]. Can you update a single array in place, and in which direction?
Show answer
Yes, by sweeping upward (j from 0 to the end). Cell j reads j and j + 1 from the old layer. Index j + 1 is later in an upward sweep, so it has not been overwritten yet, and cell j is read before it is written. A downward sweep would read an already-updated dp[j + 1].
Exercise
Running knapsack01 with weights [3, 4], values [4, 5], and capacity 7 returns 9. What would knapsackwrong_direction return, and why?
Show answer
It returns 9 as well. Capacity 7 cannot fit two copies of either item with more value than one of each: 3+3 gives 8, 4+... does not fit with another 4, and 3+4 gives 9. So the bug is hidden on this input. Raise the capacity to 8 and the wrong version returns 10 (two copies of the 4-weight item), while the correct version still returns 9. One passing test does not prove the loop direction is right.