Challenge - 5 Problems
Recursion Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Factorial Function
What is the output of the following Java code when calling
factorial(4)?DSA Java
public class Main { public static int factorial(int n) { if (n == 0) { return 1; } else { return n * factorial(n - 1); } } public static void main(String[] args) { System.out.println(factorial(4)); } }
Attempts:
2 left
💡 Hint
Remember factorial of 4 is 4 * 3 * 2 * 1.
✗ Incorrect
The factorial function multiplies n by factorial of n-1 until n is 0, where it returns 1. So factorial(4) = 4*3*2*1 = 24.
❓ Predict Output
intermediateOutput of Recursive Sum Function
What is printed when the following Java code runs
sum(3)?DSA Java
public class Main { public static int sum(int n) { if (n == 1) { return 1; } else { return n + sum(n - 1); } } public static void main(String[] args) { System.out.println(sum(3)); } }
Attempts:
2 left
💡 Hint
Sum from 1 to 3 is 1 + 2 + 3.
✗ Incorrect
The function adds n to the sum of numbers from 1 to n-1 until it reaches 1, returning 1. So sum(3) = 3 + 2 + 1 = 6.
🔧 Debug
advancedIdentify the Error in Recursive Fibonacci Function
What error will occur when running this Java code?
DSA Java
public class Main { public static int fibonacci(int n) { if (n == 0) { return 0; } else if (n == 1) { return 1; } else { return fibonacci(n - 1) + fibonacci(n - 2); } } public static void main(String[] args) { System.out.println(fibonacci(-1)); } }
Attempts:
2 left
💡 Hint
Think about what happens when n is negative.
✗ Incorrect
The function does not handle negative inputs, so calling fibonacci(-1) causes infinite recursion leading to StackOverflowError.
❓ Predict Output
advancedOutput of Recursive String Reversal
What is the output of this Java code when calling
reverse("abc")?DSA Java
public class Main { public static String reverse(String s) { if (s.isEmpty()) { return s; } else { return reverse(s.substring(1)) + s.charAt(0); } } public static void main(String[] args) { System.out.println(reverse("abc")); } }
Attempts:
2 left
💡 Hint
The function moves the first character to the end recursively.
✗ Incorrect
The function takes the first character off and appends it after reversing the rest, effectively reversing the string.
🧠 Conceptual
expertUnderstanding Base Case Importance in Recursion
Why is the base case essential in a recursive function?
Attempts:
2 left
💡 Hint
Think about what happens if recursion never stops.
✗ Incorrect
The base case stops the recursion by providing a simple answer without further calls, preventing infinite loops and stack overflow.
