4. Identify the bug in this recursive Fibonacci function without memoization:
function fib(n: number): number {
if (n === 0) return 0;
if (n === 1) return 1;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(40));
medium
A. It will cause a stack overflow error for large n.
B. It returns wrong Fibonacci numbers for n > 2.
C. It uses memoization incorrectly.
D. It has a syntax error in the return statement.
Solution
Step 1: Analyze recursion depth for fib(40)
Without memoization, fib(40) causes many repeated calls, leading to deep recursion.
Step 2: Understand consequences
Deep recursion can cause stack overflow or very slow execution, but no syntax or logic errors.
Final Answer:
It will cause a stack overflow error for large n. -> Option A
Quick Check:
Deep recursion without memo causes stack overflow [OK]
Hint: Large n without memo causes stack overflow [OK]
Common Mistakes:
Thinking it returns wrong values
Assuming syntax error exists
Confusing memoization usage
5. You want to find the minimum number of coins to make a sum using recursion. Why is dynamic programming necessary here instead of plain recursion?
function minCoins(coins: number[], sum: number): number {
if (sum === 0) return 0;
let res = Infinity;
for (let coin of coins) {
if (coin <= sum) {
let subRes = minCoins(coins, sum - coin);
if (subRes !== Infinity && subRes + 1 < res) {
res = subRes + 1;
}
}
}
return res;
}
hard
A. Because recursion cannot handle arrays as input parameters.
B. Because recursion alone recalculates the same sums multiple times, causing slow performance.
C. Because dynamic programming uses loops instead of recursion.
D. Because recursion always returns Infinity for large sums.
Solution
Step 1: Identify repeated subproblems in recursion
The function calls itself with the same sums multiple times, recalculating results.
Step 2: Explain dynamic programming benefit
DP stores results for sums already computed, avoiding repeated work and speeding up solution.
Final Answer:
Because recursion alone recalculates the same sums multiple times, causing slow performance. -> Option B
Quick Check:
DP saves repeated sum calculations [OK]
Hint: DP caches results to avoid repeated sum calculations [OK]
Common Mistakes:
Thinking recursion can't handle arrays
Believing DP replaces recursion with loops
Assuming recursion returns Infinity always
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.