Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to calculate Fibonacci numbers using simple recursion.
DSA Javascript
function fib(n) {
if (n <= 1) return n;
return fib(n - 1) [1] fib(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using subtraction or multiplication instead of addition.
Forgetting the base case for n <= 1.
✗ Incorrect
The Fibonacci sequence is calculated by adding the two previous numbers, so the operator must be '+'.
2fill in blank
mediumComplete the code to store computed Fibonacci values in a cache object.
DSA Javascript
function fibMemo(n, cache = {}) {
if (n <= 1) return n;
if (cache[n] !== undefined) return cache[n];
cache[n] = fibMemo(n - 1, cache) [1] fibMemo(n - 2, cache);
return cache[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Not storing the result in cache.
Using wrong operators causing incorrect results.
✗ Incorrect
We add the two previous Fibonacci numbers and store the result in cache[n].
3fill in blank
hardFix the error in the recursive Fibonacci function to avoid repeated calculations.
DSA Javascript
function fib(n, cache = {}) {
if (n <= 1) return n;
if ([1]) return cache[n];
cache[n] = fib(n - 1, cache) + fib(n - 2, cache);
return cache[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using loose equality which can cause false negatives.
Checking for null instead of undefined.
✗ Incorrect
We check if cache[n] is not undefined to know if the value was computed before.
4fill in blank
hardFill both blanks to create a bottom-up dynamic programming solution for Fibonacci.
DSA Javascript
function fibDP(n) {
const dp = [0, 1];
for (let i = 2; i [1] n; i++) {
dp[i] = dp[i - 1] [2] dp[i - 2];
}
return dp[n];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using < causes an off-by-one error.
Using subtraction instead of addition.
✗ Incorrect
The loop runs while i <= n, and each dp[i] is the sum of dp[i-1] and dp[i-2].
5fill in blank
hardFill all three blanks to optimize Fibonacci calculation using constant space.
DSA Javascript
function fibOptimized(n) {
if (n <= 1) return n;
let a = 0, b = 1, temp;
for (let i = 2; i [1] n; i++) {
temp = a;
a = b;
b = b [2] temp;
}
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning a instead of b.
Using < causing insufficient iterations.
Using wrong operator instead of +.
✗ Incorrect
Loop runs while i <= n, b is updated by adding temp (old a), and we return b as the nth Fibonacci number.
