Challenge - 5 Problems
Fibonacci Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Fibonacci Recursive Call
What is the output of the following C code that prints Fibonacci numbers using recursion?
DSA C
#include <stdio.h> int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } int main() { for (int i = 0; i < 6; i++) { printf("%d ", fib(i)); } return 0; }
Attempts:
2 left
💡 Hint
Remember that fib(0) = 0 and fib(1) = 1 in this code.
✗ Incorrect
The function fib returns 0 for n=0 and 1 for n=1. The loop prints fib(0) to fib(5), which are 0,1,1,2,3,5.
❓ Predict Output
intermediate1:30remaining
Value of fib(4)
What is the value returned by fib(4) in the following recursive Fibonacci function?
DSA C
int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); }
Attempts:
2 left
💡 Hint
Calculate fib(3) + fib(2) to get fib(4).
✗ Incorrect
fib(4) = fib(3) + fib(2) = (2) + (1) = 3.
🔧 Debug
advanced2:00remaining
Identify the error in Fibonacci recursion
What error will the following code produce when compiled and run?
DSA C
#include <stdio.h> int fib(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return fib(n - 1) + fib(n - 3); } int main() { printf("%d", fib(4)); return 0; }
Attempts:
2 left
💡 Hint
Check the recursive calls and their arguments.
✗ Incorrect
The function calls fib(n-3) which can cause negative arguments leading to infinite recursion and stack overflow.
🧠 Conceptual
advanced1:30remaining
Time Complexity of Recursive Fibonacci
What is the time complexity of the naive recursive Fibonacci function fib(n) 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, O(2^n).
🚀 Application
expert2:30remaining
Output of Memoized Fibonacci Calls
Given the following C code implementing Fibonacci with memoization, what is the output printed by the program?
DSA C
#include <stdio.h> int memo[6] = {0}; int fib(int n) { if (n <= 1) return n; if (memo[n] != 0) return memo[n]; memo[n] = fib(n - 1) + fib(n - 2); return memo[n]; } int main() { for (int i = 0; i < 6; i++) { printf("%d ", fib(i)); } return 0; }
Attempts:
2 left
💡 Hint
Memoization stores previously computed results to avoid repeated work.
✗ Incorrect
The memo array caches fib values. The output is the same as naive recursion but computed efficiently: 0 1 1 2 3 5.