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 Function
What is the output of the following JavaScript code that uses recursion to sum numbers from 1 to n?
DSA Javascript
function recursiveSum(n) {
if (n <= 1) return n;
return n + recursiveSum(n - 1);
}
console.log(recursiveSum(4));Attempts:
2 left
💡 Hint
Think about how the function adds n to the sum of all numbers before it.
✗ Incorrect
The function adds n to the sum of numbers from 1 to n-1 recursively. For n=4, it calculates 4 + 3 + 2 + 1 = 10.
❓ Predict Output
intermediateOutput of Recursive Factorial Function
What will be printed when the following recursive factorial function is called with 5?
DSA Javascript
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5));Attempts:
2 left
💡 Hint
Factorial multiplies all numbers from n down to 1.
✗ Incorrect
factorial(5) = 5 * 4 * 3 * 2 * 1 = 120.
🔧 Debug
advancedIdentify the Error in Recursive Fibonacci Function
What error will this code produce when calling fibonacci(5)?
DSA Javascript
function fibonacci(n) {
if (n <= 1) return n;
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(5));Attempts:
2 left
💡 Hint
Trace the calls for fibonacci(5) carefully.
✗ Incorrect
The function correctly computes fibonacci(5) = 5 by summing fibonacci(4) and fibonacci(3).
❓ Predict Output
advancedOutput of Recursive Function with Multiple Calls
What is the output of this code that prints numbers during recursion?
DSA Javascript
function printNumbers(n) {
if (n === 0) return;
console.log(n);
printNumbers(n - 1);
console.log(n);
}
printNumbers(3);Attempts:
2 left
💡 Hint
Notice the two console.log calls: one before and one after the recursive call.
✗ Incorrect
The function prints n before going deeper and after returning, so output is 3 2 1 1 2 3.
🧠 Conceptual
expertMaximum Call Stack Size Exceeded Error Cause
Which of the following causes a 'Maximum call stack size exceeded' error in recursive functions?
Attempts:
2 left
💡 Hint
Think about what happens if recursion never stops.
✗ Incorrect
Without a base case, recursion never ends, causing the call stack to overflow.
