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 Simple Recursive Sum Function
What is the output of the following TypeScript code that uses recursion to sum numbers from n down to 1?
DSA Typescript
function recursiveSum(n: number): number {
if (n <= 0) return 0;
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 below it.
✗ Incorrect
The function adds n to the sum of numbers from n-1 down to 1 recursively. For n=4, it calculates 4 + 3 + 2 + 1 = 10.
❓ Predict Output
intermediate2:00remaining
Output of Recursive Factorial Function
What will be printed when this recursive factorial function is called with 3?
DSA Typescript
function factorial(n: number): number {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log(factorial(3));Attempts:
2 left
💡 Hint
Factorial multiplies n by factorial of n-1 until it reaches 0.
✗ Incorrect
factorial(3) = 3 * factorial(2) = 3 * 2 * factorial(1) = 3 * 2 * 1 * factorial(0) = 3 * 2 * 1 * 1 = 6.
🔧 Debug
advanced2:00remaining
Identify the Error in Recursive Fibonacci Function
What is the output of this TypeScript code when calling fibonacci(5)?
DSA Typescript
function fibonacci(n: number): number {
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 sum results.
✗ Incorrect
fibonacci(5) = fibonacci(4) + fibonacci(3) = 3 + 2 = 5. The code runs correctly without errors.
❓ Predict Output
advanced2:00remaining
Output of Recursive Function with Multiple Calls
What is the output of this recursive function that prints numbers during the call and return phases?
DSA Typescript
function printNumbers(n: number): void {
if (n <= 0) return;
console.log('Call:', n);
printNumbers(n - 1);
console.log('Return:', n);
}
printNumbers(3);Attempts:
2 left
💡 Hint
Notice the order of console.log before and after the recursive call.
✗ Incorrect
The function prints 'Call:' before going deeper and 'Return:' after returning from recursion, so calls print down then returns print up.
🧠 Conceptual
expert2:00remaining
Maximum Call Stack Depth in Recursive Function
Consider this recursive function without a base case. What will happen when calling infiniteRecursion(1)?
DSA Typescript
function infiniteRecursion(n: number): number {
return infiniteRecursion(n + 1) + 1;
}
infiniteRecursion(1);Attempts:
2 left
💡 Hint
Think about what happens when recursion never stops.
✗ Incorrect
Without a base case, the function calls itself endlessly until the system runs out of stack space, causing a RangeError.