Challenge - 5 Problems
Fibonacci Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Fibonacci Recursive Call
What is the output of the following JavaScript code that calculates Fibonacci numbers recursively?
DSA Javascript
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(5));Attempts:
2 left
💡 Hint
Remember the Fibonacci sequence starts with 0, 1, 1, 2, 3, 5, 8...
✗ Incorrect
fib(5) returns fib(4) + fib(3). fib(4) is 3 and fib(3) is 2, so total is 5. The correct output is 5.
❓ Predict Output
intermediateOutput of Fibonacci Recursive Call with n=7
What is the output of this JavaScript code that calculates Fibonacci numbers recursively?
DSA Javascript
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(7));Attempts:
2 left
💡 Hint
Recall the Fibonacci sequence: 0,1,1,2,3,5,8,13,21...
✗ Incorrect
fib(7) returns the 7th Fibonacci number which is 13.
🔧 Debug
advancedIdentify the Error in Fibonacci Recursive Function
What error will this JavaScript code produce when run?
DSA Javascript
function fib(n) {
if (n < 1) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(5));Attempts:
2 left
💡 Hint
Check the base case condition carefully.
✗ Incorrect
The base case is incorrect. It should be n <= 1 to stop recursion. With n < 1, fib(1) calls fib(0) and fib(-1), and fib(-1) calls fib(-2) and so on, causing infinite recursion.
🧠 Conceptual
advancedTime Complexity of Recursive Fibonacci
What is the time complexity of the naive recursive Fibonacci function?
Attempts:
2 left
💡 Hint
Think about 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.
🚀 Application
expertOutput of Memoized Fibonacci Recursive Function
What is the output of this JavaScript code using memoization to calculate Fibonacci numbers?
DSA Javascript
function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n]) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}
console.log(fib(10));Attempts:
2 left
💡 Hint
Memoization stores results to avoid repeated calculations.
✗ Incorrect
fib(10) returns the 10th Fibonacci number which is 55.
