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
intermediateOutput of Recursive Fibonacci Function
What is the output of this C++ code that calculates Fibonacci numbers using recursion?
DSA C++
#include <iostream> int fib(int n) { if (n <= 1) return n; return fib(n-1) + fib(n-2); } int main() { int result = fib(5); std::cout << result << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Trace the recursive calls for fib(5).
✗ Incorrect
The Fibonacci sequence starts 0,1,1,2,3,5,8,... fib(5) = fib(4)+fib(3) = 3+2 = 5.
🧠 Conceptual
intermediateChoosing Between Greedy and Dynamic Programming
Which problem characteristic suggests that a greedy algorithm is NOT suitable and dynamic programming should be used instead?
Attempts:
2 left
💡 Hint
Think about when greedy fails and DP helps.
✗ Incorrect
Dynamic programming is needed when subproblems overlap and optimal substructure exists, which greedy alone cannot handle.
🔧 Debug
advancedWhy Does This Greedy Coin Change Fail?
What is the output of this code that tries to find minimum coins for amount 6 using greedy with coins {1, 3, 4}?
DSA C++
#include <iostream> int minCoins(int amount) { int coins[] = {4, 3, 1}; int count = 0; for (int i = 0; i < 3; i++) { while (amount >= coins[i]) { amount -= coins[i]; count++; } } return count; } int main() { std::cout << minCoins(6) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Check how greedy picks coins for 6.
✗ Incorrect
Greedy picks 4 once, then 1 twice, total 3 coins. But optimal is 2 coins (3+3).
❓ Predict Output
advancedOutput of Memoized Fibonacci (DP) Implementation
What is the output of this C++ code using memoization to compute fib(6)?
DSA C++
#include <iostream> #include <vector> int fib(int n, std::vector<int>& memo) { if (n <= 1) return n; if (memo[n] != -1) return memo[n]; memo[n] = fib(n-1, memo) + fib(n-2, memo); return memo[n]; } int main() { int n = 6; std::vector<int> memo(n+1, -1); std::cout << fib(n, memo) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Memoization avoids repeated calls.
✗ Incorrect
fib(6) = fib(5)+fib(4) = 5+3 = 8.
🧠 Conceptual
expertIdentifying When Greedy Algorithm Guarantees Optimal Solution
Which condition ensures that a greedy algorithm always produces an optimal solution?
Attempts:
2 left
💡 Hint
Greedy works when local choices lead to global optimum.
✗ Incorrect
Greedy algorithms work optimally when the greedy-choice property and optimal substructure hold.
