Factorial of a Number
Given a non-negative integer n, return n! — the product of every positive integer up to n, with 0! = 1 by definition. The base case is n ≤ 1, which returns 1 directly. The recursive case returns n times factorial(n - 1) — but that multiplication cannot happen until the smaller call returns, so every call waits on the call stack for the answer to a slightly smaller problem.
Constraints
- 0 ≤ n ≤ 12
Example
n = 5120Explanation 5 × 4 × 3 × 2 × 1 = 120.
In plain terms
- Base case
- The smallest version of the problem, simple enough to answer directly without recursing further.
- Call stack
- The pending calls, each waiting for its own recursive call to return before it can finish its own work.
Recurse down to the base case, then multiply on the way back up
factorial(5) is not the base case, so it calls factorial(4) and waits.
What happens in this step
factorial(5) calls factorial(4) n = 5 is not ≤ 1, so this is the recursive case. factorial(5) must wait for factorial(4) to return before it can multiply.
Steps to visualize
- Call factorial(n) — if n is 0 or 1, that is the base case: return 1 immediately.
- Otherwise call factorial(n - 1) and wait — you cannot multiply by n until that smaller call returns.
- Each waiting call sits on the call stack, holding onto its own n.
- When the base case returns 1, the calls unwind one by one, each multiplying its n by the value it received.
- The outermost call returns the final product once every pending call has resolved.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
factorial(5) is not the base case, so it calls factorial(4) and waits.
What happens in this step
factorial(5) calls factorial(4) n = 5 is not ≤ 1, so this is the recursive case. factorial(5) must wait for factorial(4) to return before it can multiply.
Solution
function factorial(n) {
if (n <= 1) {
return 1; // base case
}
return n * factorial(n - 1); // recursive case
}- Time
- O(n)
- Space
- O(n)
Test cases
| Input | Expected | Covers |
|---|---|---|
n = 5 | 120 | example from the docstring |
n = 0 | 1 | base case, 0! is defined as 1 |
n = 1 | 1 | base case, 1! is 1 |
n = 2 | 2 | one recursive call before hitting the base case |
n = 3 | 6 | a couple of calls deep |
n = 6 | 720 | several calls deep on the stack |
n = 12 | 479001600 | upper bound of the constraint range |