Challenge - 5 Problems
Recursion Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive vs Loop Factorial
What is the output of the following JavaScript code that calculates factorial using recursion and a loop?
DSA Javascript
function factorialRecursive(n) {
if (n <= 1) return 1;
return n * factorialRecursive(n - 1);
}
function factorialLoop(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorialRecursive(5));
console.log(factorialLoop(5));Attempts:
2 left
💡 Hint
Both functions calculate factorial of 5, which is 5*4*3*2*1.
✗ Incorrect
Both recursive and loop functions correctly compute factorial of 5, which is 120.
🧠 Conceptual
intermediateWhy Recursion is Needed for Tree Traversal
Why is recursion often preferred over loops for traversing tree structures?
Attempts:
2 left
💡 Hint
Think about how trees have branches and sub-branches.
✗ Incorrect
Recursion naturally handles hierarchical structures like trees by calling itself on each branch, while loops need extra stacks or queues to track nodes.
🔧 Debug
advancedIdentify the Error in Recursive Fibonacci
What error will this recursive Fibonacci function cause when called with fibonacci(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
Trace fibonacci(5) calls and their returns.
✗ Incorrect
The function correctly returns fibonacci(5) = 5 by summing fibonacci(4) and fibonacci(3).
❓ Predict Output
advancedOutput of Recursive Flattening of Nested Arrays
What is the output of this recursive function that flattens nested arrays?
DSA Javascript
function flatten(arr) {
let result = [];
for (let item of arr) {
if (Array.isArray(item)) {
result = result.concat(flatten(item));
} else {
result.push(item);
}
}
return result;
}
console.log(flatten([1, [2, [3, 4], 5], 6]));Attempts:
2 left
💡 Hint
The function collects all nested elements into one flat array.
✗ Incorrect
The function recursively concatenates all nested arrays into a single flat array.
🧠 Conceptual
expertWhy Some Problems Cannot Be Cleanly Solved with Loops Alone
Which of the following best explains why some problems require recursion instead of just loops?
Attempts:
2 left
💡 Hint
Think about problems like parsing nested structures or exploring trees.
✗ Incorrect
Recursion matches the problem structure directly when subproblems are nested and variable in depth, while loops need extra data structures and complex logic.
