Step 1: Call fib(5), check cache (empty), compute fib(4) and fib(3)
cache: {}
fib(5) -> fib(4) + fib(3)Why: We start with fib(5) and need fib(4) and fib(3) to compute it
Step 2: Call fib(4), check cache (empty), compute fib(3) and fib(2)
cache: {}
fib(4) -> fib(3) + fib(2)Why: fib(4) depends on fib(3) and fib(2), so we compute those next
Step 3: Call fib(3), check cache (empty), compute fib(2) and fib(1)
cache: {}
fib(3) -> fib(2) + fib(1)Why: fib(3) depends on fib(2) and fib(1), so we compute those
Step 4: Call fib(2), base case returns 1, store fib(2)=1 in cache
cache: {2:1}
fib(2) = 1Why: fib(2) is a base case, so we return 1 and save it
Step 5: Call fib(1), base case returns 1, store fib(1)=1 in cache
cache: {2:1, 1:1}
fib(1) = 1Why: fib(1) is a base case, so we return 1 and save it
Step 6: Compute fib(3) = fib(2) + fib(1) = 1 + 1 = 2, store fib(3)=2
cache: {2:1, 1:1, 3:2}
fib(3) = 2Why: We combine cached results to get fib(3) and save it
Step 7: Call fib(2), found in cache as 1, reuse it
cache: {2:1, 1:1, 3:2}
fib(2) = 1 (from cache)Why: No need to compute fib(2) again, reuse cached value
Step 8: Compute fib(4) = fib(3) + fib(2) = 2 + 1 = 3, store fib(4)=3
cache: {2:1, 1:1, 3:2, 4:3}
fib(4) = 3Why: Combine cached fib(3) and fib(2) to get fib(4) and save it
Step 9: Call fib(3), found in cache as 2, reuse it
cache: {2:1, 1:1, 3:2, 4:3}
fib(3) = 2 (from cache)Why: Reuse cached fib(3) to avoid recomputation
Step 10: Compute fib(5) = fib(4) + fib(3) = 3 + 2 = 5, store fib(5)=5
cache: {2:1, 1:1, 3:2, 4:3, 5:5}
fib(5) = 5Why: Combine cached fib(4) and fib(3) to get final answer fib(5)
Result: cache: {1:1, 2:1, 3:2, 4:3, 5:5}
Final answer: fib(5) = 5