Challenge - 5 Problems
Recursion Mastery Badge
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 this TypeScript code when calling
factorial(4)?DSA Typescript
function factorial(n: number): number {
if (n === 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}
console.log(factorial(4));Attempts:
2 left
💡 Hint
Remember factorial of 0 is 1, and factorial(n) = n * factorial(n-1).
✗ Incorrect
The function calculates factorial recursively. factorial(4) = 4 * 3 * 2 * 1 = 24.
❓ Predict Output
intermediate2:00remaining
Output of Recursive Sum Function
What is printed when this code runs:
sumTo(5)?DSA Typescript
function sumTo(n: number): number {
if (n === 1) {
return 1;
} else {
return n + sumTo(n - 1);
}
}
console.log(sumTo(5));Attempts:
2 left
💡 Hint
Sum from 1 to n is n*(n+1)/2.
✗ Incorrect
sumTo(5) = 5 + 4 + 3 + 2 + 1 = 15.
❓ Predict Output
advanced2:00remaining
Output of Recursive Fibonacci Function
What is the output of
console.log(fibonacci(6)) for this code?DSA Typescript
function fibonacci(n: number): number {
if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
console.log(fibonacci(6));Attempts:
2 left
💡 Hint
Fibonacci sequence starts 0,1,1,2,3,5,8,...
✗ Incorrect
fibonacci(6) = fibonacci(5) + fibonacci(4) = 8 + 5 = 13.
🔧 Debug
advanced2:00remaining
Identify the Error in Recursive Function
What error will this code cause when calling
countdown(3)?DSA Typescript
function countdown(n: number): void {
if (n === 0) {
console.log("Done!");
} else {
console.log(n);
countdown(n);
}
}
countdown(3);Attempts:
2 left
💡 Hint
Check if the recursive call changes the argument.
✗ Incorrect
The function calls countdown(n) without reducing n, causing infinite recursion.
🧠 Conceptual
expert2:00remaining
Understanding Base Case Importance
Why is the base case essential in a recursive function?
Attempts:
2 left
💡 Hint
Think about what happens if recursion never stops.
✗ Incorrect
Without a base case, recursion never ends and causes errors.