Challenge - 5 Problems
Recursion Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Simple Recursive Sum
What is the output of the following Java code that uses recursion to sum numbers from 1 to n?
DSA Java
public class Main { public static int sum(int n) { if (n == 0) return 0; return n + sum(n - 1); } public static void main(String[] args) { System.out.println(sum(4)); } }
Attempts:
2 left
💡 Hint
Think about how the function adds numbers from n down to 0.
✗ Incorrect
The function sums 4 + 3 + 2 + 1 + 0 = 10. It stops when n reaches 0.
❓ Predict Output
intermediateOutput of Recursive Factorial Function
What will be printed when the following Java program runs?
DSA Java
public class Main { public static int factorial(int n) { if (n <= 1) return 1; return n * factorial(n - 1); } public static void main(String[] args) { System.out.println(factorial(5)); } }
Attempts:
2 left
💡 Hint
Factorial multiplies all numbers from n down to 1.
✗ Incorrect
5! = 5 * 4 * 3 * 2 * 1 = 120.
🔧 Debug
advancedIdentify the Error in Recursive Fibonacci
The following Java code tries to print the 6th Fibonacci number using recursion. What error will it cause?
DSA Java
public class Main { public static int fib(int n) { if (n == 0) return 0; if (n == 1) return 1; return fib(n - 1) + fib(n - 2); } public static void main(String[] args) { System.out.println(fib(6)); } }
Attempts:
2 left
💡 Hint
Trace the calls for fib(6) carefully.
✗ Incorrect
fib(6) = fib(5) + fib(4) = 5 + 3 = 8. No error occurs.
❓ Predict Output
advancedOutput of Recursive String Reverse
What is the output of this Java program that reverses a string recursively?
DSA Java
public class Main { public static String reverse(String s) { if (s.isEmpty()) return s; return reverse(s.substring(1)) + s.charAt(0); } public static void main(String[] args) { System.out.println(reverse("code")); } }
Attempts:
2 left
💡 Hint
Each recursive call removes the first character and adds it at the end.
✗ Incorrect
The function reverses the string by moving first character to the end recursively.
🧠 Conceptual
expertMaximum Call Stack Depth in Recursive Calls
Consider this recursive Java method that counts down from n to 0. What is the maximum number of active calls on the call stack when calling countdown(5)?
DSA Java
public class Main { public static void countdown(int n) { if (n < 0) return; countdown(n - 1); } public static void main(String[] args) { countdown(5); } }
Attempts:
2 left
💡 Hint
Count how many calls happen before the base case stops recursion.
✗ Incorrect
Calls happen for n=5,4,3,2,1,0 before stopping at n=-1. So 6 calls active at peak.
