Challenge - 5 Problems
Fibonacci Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Fibonacci Call
What is the output of the following C++ code snippet that calculates Fibonacci numbers recursively?
DSA C++
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
Remember the Fibonacci sequence starts with 0, 1, 1, 2, 3, 5, 8...
✗ Incorrect
fib(5) returns 5 (the 5th Fibonacci number, 0-indexed: 0,1,1,2,3,5). The output is 5.
❓ Predict Output
intermediateOutput of Recursive Fibonacci with Negative Input
What happens when the following recursive Fibonacci function is called with n = -1?
DSA C++
int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } int main() { int result = fib(-1); std::cout << result << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Check the base case condition for n <= 1.
✗ Incorrect
The base case returns n if n <= 1. Since -1 <= 1, fib(-1) returns -1 immediately without recursion.
🔧 Debug
advancedIdentify the Error in Fibonacci Recursive Function
What error will the following C++ code produce when compiled and run?
DSA C++
int fib(int n) { if (n == 0) return 0; if (n == 1) return 1; return fib(n - 1) + fib(n - 3); } int main() { std::cout << fib(4) << std::endl; return 0; }
Attempts:
2 left
💡 Hint
Check the recursive calls and base cases carefully.
✗ Incorrect
The function calls fib(n - 3) but has no base case for n < 0, causing infinite recursion and stack overflow.
🧠 Conceptual
advancedTime Complexity of Recursive Fibonacci
What is the time complexity of the naive recursive Fibonacci function defined as fib(n) = fib(n-1) + fib(n-2) with base cases fib(0)=0 and fib(1)=1?
Attempts:
2 left
💡 Hint
Consider how many calls are made for each fib(n).
✗ Incorrect
Each call to fib(n) makes two calls to fib(n-1) and fib(n-2), leading to exponential growth in calls, so time complexity is O(2^n).
🚀 Application
expertMemoization to Optimize Recursive Fibonacci
Which of the following C++ code snippets correctly implements memoization to optimize the recursive Fibonacci function?
Attempts:
2 left
💡 Hint
Memo array must be initialized outside recursion and passed correctly.
✗ Incorrect
Option A correctly initializes a vector memo with -1, passes it by reference, and uses it to store computed values. Option A uses static vector but does not handle initialization properly for multiple calls. Option A initializes memo inside function each call, losing memoization. Option A uses 0 as default but 0 is a valid Fibonacci number, causing incorrect memo checks.
