Dynamic Programming21 sections · 916 units
Open in Course

Memoization - Time Complexity

O(n) now!

With memoization, your time complexity (how the running time grows with input size) drops from O(2n)O(2^n) to O(n)O(n). Why? Because each value from fib(0) to fib(n) is computed exactly once. The first time you call fib(k), you do the work and store it.

Every subsequent call to fib(k) is a constant-time lookup. Since there are n+1 distinct values to compute, and each takes O(1)O(1) work after memoization, you get O(n)O(n) total time.

That's exponential to linear. A huge difference. For n=40n=40: before, over 300300 million calls. After, exactly 4141 calls (one for each value from 00 to 4040). Let that sink in. fib(50) and even fib(100) now compute in milliseconds.