Skip to lesson

Saving space in DP

Space optimization analyzes state dependencies to discard historic table cells, slashing memory consumption without increasing runtime.

Rolling variables for fixed-window recurrences

Space optimisation in dynamic programming keeps only the table cells that later steps still read, such as two variables or one row, so memory drops from O(n) to O(1) or from O(m * n) to O(n).

Many dynamic programming recurrences exhibit strictly bounded lookback windows. In Fibonacci and House Robber, state i depends only on i - 1 and i - 2. Allocating a full array of size n retains obsolete data that is never read again.

Step by step

Step 1 of 5

Array: 0, 1.
prev2
0
prev1
1
Initial window: prev2 = 0, prev1 = 1. Window spans indices 0 and 1.

Example 1 · Fibonacci Space Optimization

FibonacciRolling.javaJava
public class FibonacciRolling {    public static int fib(int n) {        if (n <= 1) return n;        int prev2 = 0;        int prev1 = 1;        for (int i = 2; i <= n; i++) {            int current = prev1 + prev2;            prev2 = prev1;            prev1 = current;        }        return prev1;    }
    public static void main(String[] args) {        System.out.println("Fib(6): " + fib(6));        System.out.println("Fib(10): " + fib(10));        System.out.println("Fib(15): " + fib(15));    }}
Output
Fib(6): 8
Fib(10): 55
Fib(15): 610

What this code does

  • Variables prev2 and prev1 hold values for i - 2 and i - 1.
  • Each loop step updates the window in constant O(1) space.
  • Results 8, 55, and 610 match Fibonacci numbers for 6, 10, and 15.

Replace the array with two primitive variables, prev2 and prev1. In each iteration, compute current from the rolling variables. Then shift the window: assign prev2 = prev1, and prev1 = current. This transformation reduces auxiliary space from O(n) to constant O(1). It completely eliminates heap memory allocation and garbage collection overhead. CPU registers can often host the rolling variables directly, speeding up execution.

Trace the code

Watch two variables roll forward

Step through the program and watch prev2 and prev1.

public class RollingFib {
public static void main(String[] args) {
int prev2 = 0;
int prev1 = 1;
for (int i = 2; i <= 6; i++) {
int current = prev1 + prev2;
prev2 = prev1;
prev1 = current;
}
System.out.println(prev1);
}
}

Variables

prev2
0

Output

(nothing printed yet)

Line 3prev2 starts as fib(0) = 0.

Step 1 of 18

Sliding arrays and in-place updates

When state transitions span two dimensions, table memory often scales quadratically. In grid path problems, row i depends exclusively on row i - 1. Maintaining the entire m by n matrix consumes unnecessary memory.

Example 2 · Unique Paths with One Row Array

UniquePathsSliding.javaJava
import java.util.Arrays;
public class UniquePathsSliding {    public static int uniquePaths(int m, int n) {        int[] dp = new int[n];        Arrays.fill(dp, 1);
        for (int i = 1; i < m; i++) {            for (int j = 1; j < n; j++) {                dp[j] += dp[j - 1];            }        }        return dp[n - 1];    }
    public static void main(String[] args) {        System.out.println("Paths for 3x7: " + uniquePaths(3, 7));        System.out.println("Paths for 3x2: " + uniquePaths(3, 2));        System.out.println("Paths for 3x3: " + uniquePaths(3, 3));    }}
Output
Paths for 3x7: 28
Paths for 3x2: 3
Paths for 3x3: 6

What this code does

  • A single 1D array of size n replaces the m by n grid matrix.
  • Adding dp[j - 1] to dp[j] combines left cell with above cell in-place.
  • Outputs 28, 3, and 6 match combinatoric path counts.

Example 3 · Knapsack 1D Array Optimization

KnapsackInPlace.javaJava
public class KnapsackInPlace {    public 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];            int v = values[i];            for (int c = capacity; c >= w; c--) {                dp[c] = Math.max(dp[c], dp[c - w] + v);            }        }        return dp[capacity];    }
    public static void main(String[] args) {        int[] w = {1, 2, 3};        int[] v = {6, 10, 12};        System.out.println("Max value for cap 5: " + knapsack(w, v, 5));        int[] w2 = {2, 3, 4};        int[] v2 = {3, 4, 5};        System.out.println("Max value for cap 5 (set 2): " + knapsack(w2, v2, 5));    }}
Output
Max value for cap 5: 22
Max value for cap 5 (set 2): 7

What this code does

  • Looping backward from capacity to w prevents reusing item i multiple times.
  • Cell dp[c - w] represents the state from the previous item iteration.
  • Capacities yield optimal item bundles with values 22 and 7.

Maintain a single 1D array of size n representing the active row. As you iterate through column j, array cell dp[j] holds the previous row value. Cell dp[j - 1] holds the newly computed value for the current row. In 0/1 knapsack, iterate backward from capacity down to item weight. Backward iteration guarantees cell dp[w - weight] has not yet updated in the current round. This prevents accidental duplicate usage of single-use items in a single 1D array.

Situations where space cannot be discarded

Space optimization is not universally applicable to all dynamic programming algorithms. When a problem requires unbounded lookback, historic cells cannot be discarded. In Longest Increasing Subsequence, state i inspects every preceding cell from 0 to i - 1.

Another barrier is complete path or solution reconstruction. If an interview requires printing the actual optimal sequence, full tables are necessary. Parent pointers and transition decisions must be preserved to trace backwards.

Discarding memory is also difficult when subproblem queries arrive out of order. Always inspect the dependency graph before dropping table storage. Optimize space only after proving that earlier states are permanently obsolete.

Next step

Check your understanding

10 quick questions