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 Array Sum
What is the output of the following JavaScript code that sums elements of an array recursively?
DSA Javascript
function recursiveSum(arr, index = 0) { if (index === arr.length) return 0; return arr[index] + recursiveSum(arr, index + 1); } console.log(recursiveSum([1, 2, 3, 4]));
Attempts:
2 left
💡 Hint
Think about how the function adds each element starting from index 0 until the end.
✗ Incorrect
The function adds the current element to the sum of the rest of the array recursively. For [1,2,3,4], the sum is 1+2+3+4 = 10.
❓ Predict Output
intermediateOutput of Recursive String Reverse
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 and puts it at the end after reversing the rest.
✗ Incorrect
The function calls itself on the substring excluding the first character, then adds the first character at the end, effectively reversing the string.
❓ Predict Output
advancedOutput of Recursive Array Flattening
What is the output of the following code that flattens a nested array recursively?
DSA Javascript
function flatten(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
result = result.concat(flatten(arr[i]));
} else {
result.push(arr[i]);
}
}
return result;
}
console.log(flatten([1, [2, [3, 4], 5], 6]));Attempts:
2 left
💡 Hint
Check how the function handles nested arrays and concatenates results.
✗ Incorrect
The function correctly flattens the nested array by recursively concatenating inner arrays. The output is a flat array with all elements.
❓ Predict Output
advancedOutput of Recursive Palindrome Check
What is the output of this recursive function that checks if a string is a palindrome?
DSA Javascript
function isPalindrome(str) { if (str.length <= 1) return true; if (str[0] !== str[str.length - 1]) return false; return isPalindrome(str.slice(1, -1)); } console.log(isPalindrome("racecar"));
Attempts:
2 left
💡 Hint
The function compares first and last characters and checks the middle recursively.
✗ Incorrect
The function returns true because "racecar" reads the same forwards and backwards.
🧠 Conceptual
expertRecursion Depth for Large Arrays
What is the main risk of using simple recursion to process very large arrays in JavaScript?
Attempts:
2 left
💡 Hint
Think about how JavaScript handles function calls and memory for recursion.
✗ Incorrect
JavaScript has a limited call stack size. Too many recursive calls cause a stack overflow error.
