Challenge - 5 Problems
Factorial Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this factorial function call?
Consider the following TypeScript code that calculates factorial using recursion. What will be printed when calling factorial(4)?
DSA Typescript
function factorial(n: number): number {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(4));Attempts:
2 left
💡 Hint
Remember factorial of n is n * factorial of (n-1), and factorial of 0 is 1.
✗ Incorrect
The factorial of 4 is 4 * 3 * 2 * 1 = 24. The function calls itself reducing n by 1 until it reaches 0, then returns 1.
❓ Predict Output
intermediate2:00remaining
What is the output of factorial(0)?
Using the same factorial function, what will be printed when calling factorial(0)?
DSA Typescript
function factorial(n: number): number {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(0));Attempts:
2 left
💡 Hint
Factorial of zero is defined as 1.
✗ Incorrect
The base case returns 1 when n is 0, so factorial(0) returns 1.
🔧 Debug
advanced2:00remaining
What error does this factorial function cause?
Examine this factorial function. What error will occur when calling factorial(0)?
DSA Typescript
function factorial(n: number): number {
if (n === 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(0));Attempts:
2 left
💡 Hint
Check the base case condition and what happens when n reaches 0.
✗ Incorrect
The base case stops recursion only when n is 1. When n reaches 0, the function calls factorial(-1), then factorial(-2), and so on, causing infinite recursion and stack overflow.
🧠 Conceptual
advanced2:00remaining
How many times is factorial called when factorial(5) is executed?
Using the standard recursive factorial function, how many total calls to factorial are made when calculating factorial(5)?
DSA Typescript
function factorial(n: number): number {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
factorial(5);Attempts:
2 left
💡 Hint
Count the initial call plus all recursive calls until base case.
✗ Incorrect
The calls are factorial(5), factorial(4), factorial(3), factorial(2), factorial(1), factorial(0). Total 6 calls.
🚀 Application
expert2:00remaining
What is the output of this modified factorial function?
This factorial function prints the current value of n before the recursive call. What is the output when calling factorial(3)?
DSA Typescript
function factorial(n: number): number {
if (n === 0) {
return 1;
}
console.log(n);
return n * factorial(n - 1);
}
factorial(3);Attempts:
2 left
💡 Hint
The function prints before calling itself with n-1.
✗ Incorrect
The function prints n starting from 3 down to 1 before reaching base case 0 which does not print.