easy

Factorial of a Number

Compute the factorial of a number using recursion.

1. Define the problem

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

Inputn = 5
Output120

Explanation 5 × 4 × 3 × 2 × 1 = 120.

2. Know the words first

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.
3. Visualize the solution

Recurse down to the base case, then multiply on the way back up

Recurse down to the base case, then multiply on the way back up
Statusfactorial(5)

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.
Step 1 of 9

Steps to visualize

  1. Call factorial(n) — if n is 0 or 1, that is the base case: return 1 immediately.
  2. Otherwise call factorial(n - 1) and wait — you cannot multiply by n until that smaller call returns.
  3. Each waiting call sits on the call stack, holding onto its own n.
  4. When the base case returns 1, the calls unwind one by one, each multiplying its n by the value it received.
  5. The outermost call returns the final product once every pending call has resolved.
4. Walk through the code

Walk through the code

Same walkthrough, now with the code. Press Next to move one step and watch which lines run.

Recurse down to the base case, then multiply on the way back up
Statusfactorial(5)

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.
Step 1 of 9
5. Solution

Solution

solution.tsTypeScript
function factorial(n) {
  if (n <= 1) {
    return 1; // base case
  }
  return n * factorial(n - 1); // recursive case
}
Time
O(n)
Space
O(n)
6. Test cases

Test cases

InputExpectedCovers
n = 5120example from the docstring
n = 01base case, 0! is defined as 1
n = 11base case, 1! is 1
n = 22one recursive call before hitting the base case
n = 36a couple of calls deep
n = 6720several calls deep on the stack
n = 12479001600upper bound of the constraint range