Challenge - 5 Problems
Dynamic Programming Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Fibonacci Without Memoization
What is the output of the following C++ code that calculates Fibonacci numbers using simple recursion without any optimization?
DSA C++
#include <iostream> int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } int main() { std::cout << fib(5) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Recall the Fibonacci sequence: 0, 1, 1, 2, 3, 5, 8, ...
✗ Incorrect
fib(0)=0, fib(1)=1, fib(2)=1, fib(3)=2, fib(4)=3, fib(5)=5. The output is 5 (option A).
❓ Predict Output
intermediateOutput of Recursive Fibonacci With Memoization
What is the output of this C++ code that calculates Fibonacci numbers using recursion with memoization?
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 = 10; std::vector<int> memo(n + 1, -1); std::cout << fib(n, memo) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Remember fib(10) in the Fibonacci sequence starting at fib(0)=0.
✗ Incorrect
fib(10) = 55 in the Fibonacci sequence starting with fib(0)=0 and fib(1)=1. Memoization avoids repeated calculations, making it efficient.
🧠 Conceptual
advancedWhy Recursion Alone Can Be Inefficient
Why does simple recursion without memoization often fail or become inefficient for problems like Fibonacci numbers?
Attempts:
2 left
💡 Hint
Think about how many times fib(2) is calculated in fib(5) without memoization.
✗ Incorrect
Simple recursion recalculates the same values many times, leading to exponential growth in calls and slow performance.
🧠 Conceptual
advancedHow Dynamic Programming Solves Recursion's Problem
How does dynamic programming improve the efficiency of recursive solutions?
Attempts:
2 left
💡 Hint
Think about how memoization helps in recursion.
✗ Incorrect
Dynamic programming saves results of subproblems so they are computed once, avoiding repeated work and improving efficiency.
🔧 Debug
expertIdentify the Problem in Recursive Fibonacci Code
What problem does the following recursive Fibonacci code have that dynamic programming solves?
DSA C++
int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); }
Attempts:
2 left
💡 Hint
Consider how many times fib(2) is called when computing fib(5).
✗ Incorrect
The code recalculates the same Fibonacci numbers many times, leading to exponential time complexity. Dynamic programming avoids this by storing results.
