Challenge - 5 Problems
Recursion Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Recursive Factorial Function
What is the output of the following TypeScript code that uses recursion to calculate factorial?
DSA Typescript
function factorial(n: number): number {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(4));Attempts:
2 left
💡 Hint
Think about how factorial multiplies numbers from n down to 1.
✗ Incorrect
The factorial of 4 is 4 * 3 * 2 * 1 = 24. The recursive function multiplies n by factorial(n-1) until n is 1.
🧠 Conceptual
intermediate2:00remaining
Why Recursion Can Express Tree Traversals More Cleanly Than Loops
Why is recursion often preferred over loops when traversing tree structures?
Attempts:
2 left
💡 Hint
Think about how trees have multiple branches and how recursion calls itself for each branch.
✗ Incorrect
Recursion fits tree traversal because each recursive call can handle one branch, making code simpler. Loops need extra data structures to track nodes.
🔧 Debug
advanced2:00remaining
Identify the Error in Recursive Fibonacci Implementation
What error does the following TypeScript code produce when run?
DSA Typescript
function fib(n: number): number {
if (n === 0) return 0;
if (n === 1) return 1;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(-1));Attempts:
2 left
💡 Hint
Consider what happens when n is negative in the recursive calls.
✗ Incorrect
The function does not handle negative inputs, so calls keep decreasing n indefinitely, causing infinite recursion and stack overflow.
🚀 Application
advanced2:00remaining
Using Recursion to Flatten Nested Arrays
Which option correctly outputs the flattened array from a nested array using recursion in TypeScript?
DSA Typescript
const nested = [1, [2, [3, 4], 5], 6]; function flatten(arr: any[]): number[] { let result: number[] = []; for (const el of arr) { if (Array.isArray(el)) { result = result.concat(flatten(el)); } else { result.push(el); } } return result; } console.log(flatten(nested));
Attempts:
2 left
💡 Hint
Flattening means removing all nested arrays and putting all elements in one list.
✗ Incorrect
The recursive function checks if an element is an array; if yes, it flattens it recursively, else it adds the element to the result.
🧠 Conceptual
expert2:00remaining
Why Some Problems Cannot Be Cleanly Solved Using Loops Alone
Which statement best explains why recursion is necessary for some problems instead of just using loops?
Attempts:
2 left
💡 Hint
Think about problems like tree traversals or divide-and-conquer algorithms.
✗ Incorrect
Recursion matches problems where the solution depends on smaller versions of the same problem, which loops cannot express without extra data structures.