Challenge - 5 Problems
Memoization Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Fibonacci with Memoization
What is the output of this code that calculates Fibonacci numbers using memoization?
DSA Python
def fib(n, memo={}): if n in memo: return memo[n] if n <= 1: return n memo[n] = fib(n-1, memo) + fib(n-2, memo) return memo[n] print(fib(5))
Attempts:
2 left
💡 Hint
Remember Fibonacci sequence starts with 0,1 and each next number is sum of previous two.
✗ Incorrect
The Fibonacci sequence starts as 0,1,1,2,3,5,... So fib(5) is 5.
❓ Predict Output
intermediateOutput of Climbing Stairs Problem
What is the output of this memoized function that counts ways to climb stairs?
DSA Python
def climb_stairs(n, memo={}): if n in memo: return memo[n] if n <= 2: return n memo[n] = climb_stairs(n-1, memo) + climb_stairs(n-2, memo) return memo[n] print(climb_stairs(4))
Attempts:
2 left
💡 Hint
Ways to climb 1 or 2 stairs are base cases.
✗ Incorrect
Ways to climb 4 stairs = ways(3) + ways(2) = 3 + 2 = 5.
🔧 Debug
advancedIdentify the error in memoized factorial
What error does this code raise when called with factorial(5)?
DSA Python
def factorial(n, memo={}): if n in memo: return memo[n] if n == 0: return 1 memo[n] = n * factorial(n-1, memo) return memo[n] print(factorial(5))
Attempts:
2 left
💡 Hint
Check how recursive calls pass the memo dictionary.
✗ Incorrect
The recursive call factorial(n-1) misses the memo argument, causing TypeError.
❓ Predict Output
advancedOutput of Memoized Coin Change Ways
What is the output of this code that counts ways to make change using memoization?
DSA Python
def coin_change(coins, amount, memo={}): if amount == 0: return 1 if amount < 0: return 0 if amount in memo: return memo[amount] ways = 0 for coin in coins: ways += coin_change(coins, amount - coin, memo) memo[amount] = ways return ways print(coin_change([1,2], 3))
Attempts:
2 left
💡 Hint
Count all combinations of coins that sum to amount.
✗ Incorrect
Ways to make 3 with coins 1 and 2 are: (1+1+1), (1+2), (2+1) = 3 ways.
🧠 Conceptual
expertMemoization Cache Behavior in Recursive Calls
Consider a memoized recursive function with a mutable default argument for memo cache. What is the main risk of using a mutable default argument like memo={} in Python for memoization?
Attempts:
2 left
💡 Hint
Think about how default arguments behave in Python functions.
✗ Incorrect
Mutable default arguments are created once and shared across calls, which can cause data from one call to affect another.
