Challenge - 5 Problems
Recursion vs Iteration Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive vs Iterative Factorial
What is the output of the following Java code that calculates factorial using recursion and iteration?
DSA Java
public class FactorialTest { public static int factorialRecursive(int n) { if (n == 0) return 1; return n * factorialRecursive(n - 1); } public static int factorialIterative(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; } public static void main(String[] args) { System.out.println(factorialRecursive(5)); System.out.println(factorialIterative(5)); } }
Attempts:
2 left
💡 Hint
Recall factorial of 5 is 5*4*3*2*1.
✗ Incorrect
Both recursive and iterative methods correctly compute factorial of 5 as 120.
🧠 Conceptual
intermediateWhen is recursion preferred over iteration?
Which scenario best explains when recursion is preferred over iteration?
Attempts:
2 left
💡 Hint
Think about problems like exploring branches or nested structures.
✗ Incorrect
Recursion is ideal for problems that break down into smaller similar problems, such as traversing trees or graphs.
❓ Predict Output
advancedStack Overflow in Deep Recursion
What error does the following Java code produce when run with input n=100000?
DSA Java
public class DeepRecursion { 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(100000)); } }
Attempts:
2 left
💡 Hint
Think about how many recursive calls happen and Java's stack size.
✗ Incorrect
Java has limited stack size; deep recursion like 100000 calls causes StackOverflowError.
🧠 Conceptual
advancedWhy iteration can be better for large input sizes?
Why is iteration often preferred over recursion for very large input sizes?
Attempts:
2 left
💡 Hint
Consider memory usage and call stack limits.
✗ Incorrect
Iteration uses loops and does not add to the call stack, so it avoids stack overflow and uses less memory for large inputs.
🔧 Debug
expertIdentify the output of mutual recursion
What is the output of this Java code using mutual recursion?
DSA Java
public class MutualRecursion { public static void even(int n) { if (n == 0) { System.out.print("Even"); } else { odd(n - 1); } } public static void odd(int n) { if (n == 0) { System.out.print("Odd"); } else { even(n - 1); } } public static void main(String[] args) { even(3); } }
Attempts:
2 left
💡 Hint
Trace the calls: even(3) calls odd(2), odd(2) calls even(1), etc.
✗ Incorrect
The calls alternate until n reaches 0 in odd(), which prints "Odd".
