Challenge - 5 Problems
Fibonacci DP Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Fibonacci with Memoization
What is the output of the following JavaScript code that calculates the 6th Fibonacci number using memoization?
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(6));Attempts:
2 left
💡 Hint
Remember that Fibonacci sequence starts with 0, 1, 1, 2, 3, 5, 8...
✗ Incorrect
The 6th Fibonacci number (starting from 0) is 8. The function uses memoization to store intermediate results and avoid repeated calculations.
❓ Predict Output
intermediateOutput of Bottom-Up Fibonacci
What will be printed by this bottom-up dynamic programming approach to Fibonacci for n=7?
DSA Javascript
function fib(n) {
const dp = [0, 1];
for (let i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
console.log(fib(7));Attempts:
2 left
💡 Hint
Count the Fibonacci sequence starting from 0 index.
✗ Incorrect
The 7th Fibonacci number is 13 in the sequence 0,1,1,2,3,5,8,13.
🧠 Conceptual
advancedWhy Use Memoization in Fibonacci?
Why is memoization important when calculating Fibonacci numbers recursively?
Attempts:
2 left
💡 Hint
Think about how many times the same Fibonacci number is calculated without memoization.
✗ Incorrect
Memoization saves results of subproblems so the function does not compute the same Fibonacci number multiple times, reducing time complexity from exponential to linear.
❓ Predict Output
advancedOutput of Fibonacci with Incorrect Memo Check
What is the output of this code that tries to use memoization but has a bug in the memo check?
DSA Javascript
function fib(n, memo = {}) {
if (n <= 1) return n;
if (memo[n] !== undefined) return memo[n];
memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
return memo[n];
}
console.log(fib(5));Attempts:
2 left
💡 Hint
Check how memo[n] is checked before returning.
✗ Incorrect
The code correctly checks if memo[n] is not undefined before returning it, so it works fine and returns 5 for fib(5).
❓ Predict Output
expertOutput of Fibonacci with Space Optimization
What is the output of this space-optimized Fibonacci function for n=10?
DSA Javascript
function fib(n) {
if (n <= 1) return n;
let a = 0, b = 1, c = 0;
for (let i = 2; i <= n; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
console.log(fib(10));Attempts:
2 left
💡 Hint
Recall the Fibonacci sequence values at index 10 starting from 0.
✗ Incorrect
The 10th Fibonacci number is 55. This code uses only three variables to calculate it efficiently.
