AlgoFrames

Space optimization: rolling rows and variables

Most DP tables only need the last row or two. Rolling arrays shrink a grid to two rows, then to one, without changing the answer.

Before you start: String DP: LCS, edit distance, palindromic subsequence.

Rolling rows: from a full table to one row

The idea

The unique-paths table for a 5 × 6 grid stores 30 numbers. The question only asks for the last one.

A 1,000 × 1,000 grid would keep a million numbers in memory. Most of them are never read again after their row is done.

Intuition

Cell (3, 3) reads the cell above in row 2 and the cell to its left in row 3. Rows 0 and 1 are never read again.

So keep two rows: prev for the row above and cur for the row being filled. After each row, cur becomes prev.

The recurrence dp[r][c] = dp[r − 1][c] + dp[r][c − 1] only looks one row back. Any table whose cells look k rows back needs k + 1 rows.

How it works

One row is enough. Before row[3] is updated it still holds 4 from the row above, and row[2] already holds the new left value 6.

Going left to right, every cell before c is already in the new row and every cell from c on is still in the old row. That is exactly the left and above the recurrence needs.

Complexity

Every version still fills rows × cols cells, so time stays O(rows · cols). Memory falls from rows · cols to 2 · cols, then to cols.

Rolling changes where results are stored, never how many are computed. Put the shorter side along the row to keep O(min(rows, cols)).

Pitfalls

Rolled rows keep only the last counts. To print the route itself, keep the full table or recompute it.

Walking back from the goal needs the values of every earlier row. Once a row is overwritten, that information is gone.

With rows = 1 the loop never runs and cur stays empty. Return prev[cols − 1], which holds the last finished row.

Variations

0/1 knapsack shrinks to one row too, with its capacity loop running from high to low. The next lesson shows why.

Longest common subsequence and edit distance roll the same way: two rows, one string along the columns.

When a value reads only the two before it, two variables replace the whole array, as in Fibonacci.

Knapsack in one row: why the loop runs backwards

The idea

0/1 knapsack fills a table: each row adds one item, each column is a capacity. The cell for item 1 at capacity 4 reads two cells in the row above.

Row + item 1 at capacity 4 compares skipping the item (15, straight above) with taking it (dp[4 − 3] = 15, plus its value 20).

Intuition

In one row, a loop going up overwrites dp[c − w] before dp[c] reads it. Item 0 then gets packed twice.

dp[1] already became 15 for item 0. dp[2] then reads 15 + 15 = 30, which means two copies of item 0.

Going down, dp[c − w] is to the left and not updated yet. It still holds the row above, so each item counts once.

So one array of capacity + 1 cells replaces the whole table, as long as each item's loop runs from high to low.

Complexity

Time stays O(n · W) for n items and capacity W. Memory drops from (n + 1)(W + 1) cells to W + 1.

Pitfalls

Looping capacities upward turns 0/1 knapsack into unbounded knapsack. Here dp[4] = 60 packs item 0 four times.

The inner loop stops at c = w. Below that the item cannot fit, and dp[c − w] would read a negative index.

Variations

When each item may be used any number of times, the upward loop is exactly right. Coin change uses it.

With two limits, weight and volume, the same backward trick keeps a 2-D table, not a 3-D one. Items are listed above the table.

Code

Pseudocode

knapsack(weights, values, capacity):
  dp ← array of capacity + 1 zeros
  for each item (w, v)
    for c ← capacity down to w
      dp[c] ← max(dp[c], dp[c - w] + v)
  return dp[capacity]

Python

def knapsack(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]

JavaScript

function knapsack(weights, values, capacity) {
  const dp = new Array(capacity + 1).fill(0);
  for (let i = 0; i < weights.length; i++) {
    const w = weights[i], v = values[i];
    for (let c = capacity; c >= w; c--) {
      dp[c] = Math.max(dp[c], dp[c - w] + v);
    }
  }
  return dp[capacity];
}

Java

static int knapsack(int[] weights, int[] values, int capacity) {
    int[] dp = new int[capacity + 1];
    for (int i = 0; i < weights.length; i++) {
        int w = weights[i], v = values[i];
        for (int c = capacity; c >= w; c--) {
            dp[c] = Math.max(dp[c], dp[c - w] + v);
        }
    }
    return dp[capacity];
}

Practice problems (7)

Why iterate in reverse Warm-up

One-row 0/1 knapsack updates dp[c] = max(dp[c], dp[c − w] + v) with c running from capacity down to w.

Why must c go downwards?

How much of the table to keep Warm-up

Match each DP to the smallest amount of its table you must keep while it runs.

Optimize unique paths Standard

A robot walks from the top-left to the bottom-right cell of grid, moving only right or down. Cells with 1 are obstacles; 0 is open.

Return the number of different paths. Use only one array as long as a row for extra memory.

Knapsack in 1-D Standard

Item i weighs weights[i] and is worth profits[i]. Each item can be packed at most once.

Return the largest total worth that fits in a bag of weight capacity. Use one array of capacity + 1 entries.

House robber in two variables Standard

Houses stand in a row and nums[i] is the money in house i. Robbing two neighbouring houses sets off an alarm.

Return the most money you can take without robbing two neighbours. Use O(1) extra memory: no array of size n.

Trace one-row knapsack Standard

Follow one-row knapsack on weights [2, 3, 4], values [3, 4, 6] and capacity 6. Answer each question before the step plays.

Edit distance in O(min(m, n)) space Challenge

Return the fewest single-letter inserts, deletes and replacements that turn word1 into word2.

Use extra memory proportional to the shorter word: O(min(m, n)) for lengths m and n.

Related topics

Next on the path: Interval DP: matrix chain, burst balloons, palindrome partitioning