Challenge - 5 Problems
Factorial Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Recursive Factorial Function Call
What is the output of the following JavaScript code that calculates factorial recursively?
DSA Javascript
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(4));Attempts:
2 left
💡 Hint
Recall that factorial of 4 is 4 * 3 * 2 * 1.
✗ Incorrect
The factorial function multiplies n by factorial of n-1 until n is 0, where it returns 1. So factorial(4) = 4*3*2*1 = 24.
❓ Predict Output
intermediateOutput When Calling Factorial with 0
What does the following recursive factorial function return when called with 0?
DSA Javascript
function factorial(n) {
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
By definition, factorial(0) returns 1 as the base case in the recursion.
❓ Predict Output
advancedOutput of Incorrect Recursive Factorial Implementation
What is the output of this code snippet?
DSA Javascript
function factorial(n) {
if (n === 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(0));Attempts:
2 left
💡 Hint
Check what happens when n is 0 and the base case is for n === 1.
✗ Incorrect
Since the base case is for n === 1, calling factorial(0) causes infinite recursion until stack overflow.
🧠 Conceptual
advancedWhy Use Recursion for Factorial?
Which of the following is the best reason to use recursion to calculate factorial?
Attempts:
2 left
💡 Hint
Think about how recursion breaks down problems.
✗ Incorrect
Recursion works well for factorial because it breaks the problem into smaller factorial calculations until reaching the base case.
❓ Predict Output
expertOutput of Memoized Recursive Factorial
What is the output of this memoized factorial function when called with 5?
DSA Javascript
const memo = {};
function factorial(n) {
if (n === 0) return 1;
if (memo[n]) return memo[n];
memo[n] = n * factorial(n - 1);
return memo[n];
}
console.log(factorial(5));Attempts:
2 left
💡 Hint
Memoization stores results to avoid repeated calculations.
✗ Incorrect
The function correctly calculates factorial(5) as 120 and stores intermediate results in memo.
