Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to make the factorial function recursive.
DSA Java
public int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial([1]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Returning 1 always ignores the recursive step.
✗ Incorrect
The factorial of n is n times factorial of n-1, so we call factorial(n - 1).
2fill in blank
mediumComplete the code to calculate the nth Fibonacci number recursively.
DSA Java
public int fibonacci(int n) {
if (n <= 1) {
return n;
} else {
return fibonacci([1]) + fibonacci(n - 2);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Using the same argument twice misses the sequence logic.
✗ Incorrect
Fibonacci of n is sum of fibonacci(n-1) and fibonacci(n-2).
3fill in blank
hardFix the error in the recursive sum function to correctly sum numbers from 1 to n.
DSA Java
public int sum(int n) { if (n == 0) { return 0; } else { return n + sum([1]); } }
Attempts:
3 left
💡 Hint
Common Mistakes
Using n + 1 causes infinite recursion.
Returning 0 always ignores the recursive step.
✗ Incorrect
To sum from 1 to n, we add n plus sum of numbers up to n-1.
4fill in blank
hardFill both blanks to create a recursive function that reverses a string.
DSA Java
public String reverse(String s) {
if (s.isEmpty()) {
return s;
} else {
return reverse(s[1]) + s.charAt([2]);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using substring(0, s.length() - 1) reverses the wrong part.
Using length() - 1 as index causes index errors.
✗ Incorrect
We reverse the substring from index 1 onward and add the first character at the end.
5fill in blank
hardFill both blanks to implement a recursive function that counts occurrences of a character in a string.
DSA Java
public int countChar(String s, char c) {
if (s.isEmpty()) {
return 0;
} else {
int count = (s.charAt([1]) == c) ? 1 : 0;
return count + countChar(s[2], c);
}
}Attempts:
3 left
💡 Hint
Common Mistakes
Using substring(0, s.length() - 1) removes the last character instead of the first.
Changing c in recursive calls causes errors.
✗ Incorrect
Check the first character at index 0, then recurse on substring from index 1, passing c unchanged.
