Dynamic Programming21 sections · 916 units
Open in Course

Memoization - Space Complexity

O(n) cost

Your space complexity (how much memory your code uses) is O(n)O(n) from two sources. - First, the dp array stores up to n+1n+1 entries, one for each subproblem. - Second, the recursive call stack can go nn levels deep before hitting the base case.

Both contribute O(n)O(n) space, so overall you use O(n)O(n) memory. This is the trade-off: you sacrifice space to gain speed.

In practice, O(n)O(n) space is manageable for most problems. The call stack depth can be a concern for large nn in languages with limited stack size, but typically it's fine. But what if recursion isn't your style? There's another way.