Challenge - 5 Problems
Recursion Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Sum Function
What is the output of the following JavaScript code that uses recursion to sum numbers from n down to 1?
DSA Javascript
function recursiveSum(n) {
if (n <= 0) {
return 0;
}
return n + recursiveSum(n - 1);
}
console.log(recursiveSum(4));Attempts:
2 left
💡 Hint
Think about what happens when n reaches 0 and how the function adds up the numbers.
✗ Incorrect
The function adds n to the sum of all numbers below it until it reaches 0, where it stops. So, 4 + 3 + 2 + 1 = 10.
❓ Predict Output
intermediateOutput of Recursive Factorial Function
What will be printed when this recursive factorial function is called with 3?
DSA Javascript
function factorial(n) {
if (n === 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(3));Attempts:
2 left
💡 Hint
Factorial means multiplying all numbers from n down to 1.
✗ Incorrect
factorial(3) = 3 * factorial(2) = 3 * 2 * factorial(1) = 3 * 2 * 1 = 6.
🔧 Debug
advancedIdentify the Error in Recursive Fibonacci Function
What error will this recursive Fibonacci function cause when called with 5?
DSA Javascript
function fibonacci(n) {
if (n === 0) {
return 0;
}
if (n === 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
console.log(fibonacci(5));Attempts:
2 left
💡 Hint
Check if the base cases cover all needed conditions to stop recursion.
✗ Incorrect
The function correctly defines base cases for 0 and 1, so it stops recursion properly and returns 5 for fibonacci(5).
❓ Predict Output
advancedOutput of Recursive String Reversal
What is the output of this recursive function that reverses a string?
DSA Javascript
function reverseString(str) { if (str === "") { return ""; } return reverseString(str.substr(1)) + str[0]; } console.log(reverseString("code"));
Attempts:
2 left
💡 Hint
The function takes the first character off and adds it to the end after reversing the rest.
✗ Incorrect
The function reverses the string by moving the first character to the end recursively. So "code" becomes "edoc".
🧠 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 the function never stops calling itself.
✗ Incorrect
The base case stops the recursion by providing a condition where the function no longer calls itself, preventing infinite loops and stack overflow.
