Challenge - 5 Problems
DP vs Recursion vs Greedy Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Recursive Fibonacci Function
What is the output of the following TypeScript code that uses recursion to calculate Fibonacci numbers?
DSA Typescript
function fib(n: number): number {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(5));Attempts:
2 left
💡 Hint
Trace the recursive calls for fib(5).
✗ Incorrect
The recursive function fib calculates Fibonacci numbers where fib(0)=0 and fib(1)=1. For fib(5), the result is 5.
🧠 Conceptual
intermediate1:30remaining
Choosing Greedy vs Dynamic Programming
Which problem characteristic best indicates that a greedy algorithm is the right choice over dynamic programming?
Attempts:
2 left
💡 Hint
Greedy algorithms work when local choices lead to global optimum.
✗ Incorrect
Greedy algorithms work best when the problem has optimal substructure but does not require solving overlapping subproblems, unlike dynamic programming.
🔧 Debug
advanced2:00remaining
Why Does This Memoized Recursive Code Fail?
Consider this TypeScript code for memoized recursion to compute factorial. What error does it produce?
DSA Typescript
function factorial(n: number, memo: {[key: number]: number} = {}): number {
if (n <= 1) return 1;
if (memo[n]) return memo[n];
memo[n] = n * factorial(n - 1, memo);
return memo[n];
}
console.log(factorial(0));Attempts:
2 left
💡 Hint
Check base case for n=0.
✗ Incorrect
The base case covers n <= 1, so factorial(0) returns 1 correctly without error.
❓ Predict Output
advanced2:00remaining
Output of Greedy Coin Change Algorithm
What is the output of this TypeScript code that uses a greedy approach to make change for 30 cents with coins [25, 10, 5, 1]?
DSA Typescript
function greedyChange(coins: number[], amount: number): number[] {
const result: number[] = [];
for (const coin of coins) {
while (amount >= coin) {
amount -= coin;
result.push(coin);
}
}
return result;
}
console.log(greedyChange([25, 10, 5, 1], 30));Attempts:
2 left
💡 Hint
Greedy picks largest coin first.
✗ Incorrect
The greedy algorithm picks 25 first, then 5 to make 30 cents.
🧠 Conceptual
expert2:30remaining
When Is Dynamic Programming Necessary Over Greedy?
Which scenario best explains when dynamic programming is necessary instead of a greedy approach?
Attempts:
2 left
💡 Hint
Dynamic programming solves overlapping subproblems efficiently.
✗ Incorrect
Dynamic programming is needed when the problem has both optimal substructure and overlapping subproblems, requiring careful reuse of solutions.