Dynamic Programming21 sections · 916 units
Open in Course

Space Optimization

Only keep what you need

Notice that to compute fib(i), you only need fib(i-1) and fib(i-2). You don't need the entire array. So instead of storing all n+1n+1 values, you can keep just two variables: prev1 (for fib(i-1)) and prev2 (for fib(i-2)). At each step, you compute the new value, then shift: prev2 = prev1, prev1 = current.

This reduces space from O(n)O(n) to O(1)O(1). This "rolling window" technique is common in DP when each value depends only on a few recent values and saves you tons of memory.