Memoized Fibonacci Practice Problem
This data science coding problem helps you practice Functions & Scope, memoized fibonacci, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Functions & Scope.
- Problem ID: 83
- Problem key: 83-memoized-fibonacci
- URL: https://datacrack.app/solve/83-memoized-fibonacci
- Difficulty: medium
- Topic: Functions & Scope
- Module: Python Fundamentals
Problem Statement
# š§© Memoized Fibonacci
---
### šÆ Goal
Naive recursive Fibonacci is exponentially slow ā `fib(35)` makes over 29 million recursive calls. **Memoization** fixes this by caching results you've already computed. This is your introduction to the **space-time tradeoff** ā a concept fundamental to efficient algorithms and ML system design.
---
### š The Problem with Naive Recursion
```
fib(5)
āāā fib(4)
ā āāā fib(3) ā computed twice!
ā ā āāā fib(2)
ā ā āāā fib(1)
ā āāā fib(2) ā computed twice!
āāā fib(3) ā computed twice!
āāā fib(2)
āāā fib(1)
```
With memoization, each sub-problem is computed **exactly once** and cached.
---
### š» Task
Implement `memoized_fibonacci(n)` using a dictionary as a cache.
---
### š„ Input
- `n`: int ā compute the nth Fibonacci number (0-indexed: fib(0) = 0, fib(1) = 1)
### š¤ Output
- int ā the nth Fibonacci number
---
### š§© Starter Code
```python
def memoized_fibonacci(n, cache=None):
"""
Compute the nth Fibonacci number using memoization.
Args:
n (int): Index of the Fibonacci number to compute
cache (dict): Memoization cache (created automatically)
Returns:
int: The nth Fibonacci number
"""
if cache is None:
cache = {}
# š§ TODO: Handle base cases (n == 0 returns 0, n == 1 returns 1)
# š§ TODO: Check if n is already in cache ā if so, return cache[n]
# š§ TODO: Compute fib(n-1) + fib(n-2), store in cache, return it
pass
```
---
### š” Example
```python
memoized_fibonacci(10) # Expected: 55
memoized_fibonacci(30) # Expected: 832040
memoized_fibonacci(35) # Expected: 9227465 (fast with memoization!)
```
---
### š Key Concepts
- Cache (dict) stores: `{n: fib(n)}` for each computed value
- Default mutable arguments (`cache=None` + `if cache is None`) ā avoid `def f(cache={})` which shares state
- This is **dynamic programming** ā top-down styleStarter Code
def memoized_fibonacci(n, cache=None):
"""
Compute the nth Fibonacci number using memoization.
Args:
n (int): Index of the Fibonacci number to compute
cache (dict): Memoization cache (created automatically)
Returns:
int: The nth Fibonacci number
"""
if cache is None:
cache = {}
# š§ TODO: Handle base cases (n == 0 returns 0, n == 1 returns 1)
# š§ TODO: Check if n is already in cache ā if so, return cache[n]
# š§ TODO: Compute fib(n-1) + fib(n-2), store in cache, return it
pass