Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to return the base case value for Fibonacci of 0.
DSA Javascript
function fibonacci(n) {
if (n === 0) {
return [1];
}
return fibonacci(n - 1) + fibonacci(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 1 instead of 0 for n=0.
Returning n which is unnecessary here.
✗ Incorrect
The Fibonacci of 0 is defined as 0, so the function should return 0 for n === 0.
2fill in blank
mediumComplete the code to return the base case value for Fibonacci of 1.
DSA Javascript
function fibonacci(n) {
if (n === 0) {
return 0;
} else if (n === 1) {
return [1];
}
return fibonacci(n - 1) + fibonacci(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Returning 0 instead of 1 for n=1.
Returning n which is unnecessary here.
✗ Incorrect
The Fibonacci of 1 is defined as 1, so the function should return 1 for n === 1.
3fill in blank
hardFix the error in the recursive call to correctly calculate Fibonacci.
DSA Javascript
function fibonacci(n) {
if (n === 0) {
return 0;
} else if (n === 1) {
return 1;
}
return fibonacci([1]) + fibonacci(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 which causes infinite recursion.
Using n which causes infinite recursion.
✗ Incorrect
The Fibonacci sequence is calculated by adding fibonacci(n-1) and fibonacci(n-2). The first recursive call must be fibonacci(n - 1).
4fill in blank
hardFill both blanks to complete the recursive Fibonacci function with base cases.
DSA Javascript
function fibonacci(n) {
if (n === [1]) {
return 0;
} else if (n === [2]) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Swapping the base cases.
Using 2 or -1 as base cases.
✗ Incorrect
The base cases for Fibonacci are n=0 returning 0 and n=1 returning 1.
5fill in blank
hardFill all three blanks to create a recursive Fibonacci function that returns the nth Fibonacci number.
DSA Javascript
function fibonacci([1]) { if ([2] === 0) { return 0; } else if (n === [3]) { return 1; } return fibonacci(n - 1) + fibonacci(n - 2); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names for parameter and conditions.
Mixing up base case values.
✗ Incorrect
The function parameter is n, the first if checks if n === 0, and the second if checks if n === 1.
