

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Still calibrating
click for more info
Not enough gems
Cost: 6 gems
1: Intro to Dynamic Programming
incomplete
2: Fast Fibonacci – Memoization
incomplete
3: Memoization
incomplete
4: Fast Fibonacci – Tabulation
incomplete
5: Fast Fibonacci – Review
incomplete
This lesson's interactive features are locked, please to keep using them
Memoization is an optimization technique used primarily to speed up programs by storing the results of expensive function calls and using cached results when the same inputs occur repeatedly.
Memoization is a specific type of caching. While caching can refer generally to any storing technique, for example web page caching, memoizing specifically involves caching the return values of a function for algorithmic use.
Adding memoization is a way to lower a function's time cost in exchange for space cost. In most cases, this means trading memory (RAM) for compute resources (CPU). Memoized functions become optimized for speed in exchange for a higher use of memory space.
def fibonacci(n: int, memo: dict[int, int] | None = None) -> int:
if memo is None:
memo = {}
if n not in memo:
if n == 0:
memo[n] = 0
elif n == 1:
memo[n] = 1
else:
memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
return memo[n]