Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to define a recursive function that counts down from n to 1.
DSA Javascript
function countdown(n) {
if (n <= 0) return;
console.log(n);
countdown([1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using n does not change the argument, causing infinite recursion.
✗ Incorrect
The function calls itself with n - 1 to count down until it reaches 0.
2fill in blank
mediumComplete the code to calculate factorial of n using recursion.
DSA Javascript
function factorial(n) {
if (n === 0) return 1;
return n * factorial([1]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Returning 0 in base case breaks factorial logic.
✗ Incorrect
Factorial multiplies n by factorial of n - 1 until n is 0.
3fill in blank
hardFix the error in the recursive Fibonacci function to correctly compute fib(n).
DSA Javascript
function fib(n) {
if (n <= 1) return n;
return fib([1]) + fib(n - 2);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using fib(n-2) twice causes wrong results.
Using fib(n) causes infinite recursion.
✗ Incorrect
Fibonacci is sum of fib(n-1) and fib(n-2). The first recursive call must be fib(n-1).
4fill in blank
hardFill both blanks to create a recursive function that sums numbers from 1 to n.
DSA Javascript
function sumToN(n) {
if (n === 0) return 0;
return n [1] sumToN([2]);
}Attempts:
3 left
💡 Hint
Common Mistakes
Using multiplication instead of addition changes the logic.
Increasing n causes infinite recursion.
✗ Incorrect
To sum numbers from 1 to n, add n to sumToN(n - 1).
5fill in blank
hardFill the blanks to create a recursive function that reverses a string.
DSA Javascript
function reverseStr(str) {
if (str.length === 0) return '';
return reverseStr(str.[1]) + str[2];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using slice(0,1) instead of slice(1) causes infinite recursion.
Adding str[0] before recursive call reverses the logic.
✗ Incorrect
The function calls reverseStr on the string without the first character (slice(1)) and adds the first character (str[0]) at the end.
