AlgoViz

Recursion: factorial

easy 16 min

Recursion is a function solving a problem by calling itself on a smaller copy of it.

Video lesson · Chapter 1 of 5

Ask the next person

0:00 / 4:18

Recursive factorial — Four tickets backstage

1:27Reel

Read caption

A backstage mouse counts four performers’ possible lineups by tracing suspended factorial calls and their return values. Hang the question on the way down. Stamp the answer on the way back.

How it works

Step through the idea, or press Play.

Step 1 of 3

Check the base case. If n is 0 or 1, the answer is 1 and nothing else is called

Understand it

Start here

What recursion is

Imagine you are in a line and someone asks how many people are in it. You cannot see the end, so you say: I am 1, plus however many people are behind me, and pass the question back. Each person does the same until the last person, with nobody behind, says just 1. Then the answers bubble back to the front. That is recursion: a function that solves a problem by calling itself on a smaller copy of the same problem.

  • Base case

    The smallest input, answered directly. It is what stops the calls.

  • Recursive case

    Shrink the problem, call yourself on the smaller piece, then combine.

  • Call stack

    Every call waiting for an answer keeps a frame on the stack until it returns.

The definition

Factorial, defined recursively

The product form

n!=n×(n−1)×(n−2)×⋯×2×1,0!=1n! = n \times (n-1) \times (n-2) \times \dots \times 2 \times 1, \qquad 0! = 1
n!n! counts the ways to order nn distinct items. There is exactly one way to order nothing, so 0!=10! = 1. More on the counting side in Factorials & trailing zeroes.

The recursive form

n!={1if n≤1(base case)n×(n−1)!if n>1(recursive case)n! = \begin{cases} 1 & \text{if } n \le 1 \quad \text{(base case)} \\ n \times (n-1)! & \text{if } n > 1 \quad \text{(recursive case)} \end{cases}
The product hides a smaller factorial: 5!=5×(4×3×2×1)=5×4!5! = 5 \times (4 \times 3 \times 2 \times 1) = 5 \times 4!. Written this way, the definition is already the code.
nn! as a smaller factorialValue
0base case1
1base case1
33×2!3 \times 2!6
44×3!4 \times 3!24
55×4!5 \times 4!120
66×5!6 \times 5!720
Each row reuses the one above it. That reuse is the recursive case.

Anatomy

Base case and recursive case

Python
def factorial(n):    """Calculate n! using recursion."""    # BASE CASE: the stopping condition    if n <= 1:        return 1          # 0! = 1 and 1! = 1    # RECURSIVE CASE: a smaller copy of the problem    return n * factorial(n - 1)print(factorial(5))       # 120print(factorial(0))       # 1
Every recursive function has these two parts. The base case comes first.
Edit and run it in your browser

One call of factorial(n), step by step

Check the base case, recurse, wait, multiply, return. Every call follows this path.

A correct base case

  • Is checked before any recursive call.
  • Is reachable from every valid input: n <= 1 catches both 0 and 1.
  • Returns the right value: 0!=1!=10! = 1! = 1, not 0.

A broken recursion

  • Has no base case, so it never stops.
  • Uses n == 1, which factorial(0) jumps straight past.
  • Calls factorial(n) instead of factorial(n - 1), so it never gets closer.

Under the hood

The call stack: winding and unwinding

Each call gets a stack frame holding its own n, the multiplication it still has to do and the place to return to. Calls pile up while the problem shrinks (winding), then pop off one by one as answers come back (unwinding). The Stack topic shows the same machinery for ordinary function calls.

factorial(4): frames pushed, then popped

The deepest call finishes first. Results bubble back up the stack in reverse order.

What each frame holds (inside factorial(3))

FrameParameterWaiting forWill compute
factorial(3)n = 3factorial(2)3×3 \times result
factorial(2)n = 2factorial(1)2×2 \times result
factorial(1)n = 1nothing: base casereturns 1
Each frame has its own n. The frames do not share variables, which is why the same name can hold three values at once.

The math

Why it works

Proof by induction

0!=1⏟basek! correct  ⇒  (k+1)!=(k+1)×k! correct⏟step\underbrace{0! = 1}_{\text{base}} \qquad \underbrace{k! \text{ correct} \;\Rightarrow\; (k+1)! = (k+1) \times k! \text{ correct}}_{\text{step}}
If the base case is right, and each step is right whenever the smaller one is, then every nn is right. For example 1!=1×0!=1×1=11! = 1 \times 0! = 1 \times 1 = 1, then 2!=2×1!=22! = 2 \times 1! = 2, and so on.
Python
def recursive_function(input):    # 1. BASE CASE: when to stop    if base_condition(input):        return base_value    # 2. SHRINK: make the problem smaller    smaller_input = reduce(input)    # 3. RECURSIVE CALL: trust that it works    sub_result = recursive_function(smaller_input)    # 4. COMBINE: build the final answer    return combine(input, sub_result)
The universal recursion template: base case, shrink, recurse, combine.

Complexity

Time and space

Time: one call per value of n

T(n)=T(n−1)+O(1)  ⇒  T(n)=O(1)+O(1)+⋯+O(1)⏟n calls=O(n)T(n) = T(n-1) + O(1) \;\Rightarrow\; T(n) = \underbrace{O(1) + O(1) + \dots + O(1)}_{n \text{ calls}} = O(n)
Each call does one comparison and one multiplication, then makes one smaller call. nn calls of constant work is O(n)O(n).

Space: the deepest the stack gets

S(n)=max depth×frame size=n×O(1)=O(n)S(n) = \text{max depth} \times \text{frame size} = n \times O(1) = O(n)
All nn frames are alive at the moment the base case runs. The loop version keeps one frame, so it is O(1)O(1) extra space.
VersionTimeExtra spaceNote
Recursive factorial(n)O(n)O(n)O(n)O(n) stackHits the recursion limit for large n
Iterative loopO(n)O(n)O(1)O(1)The default choice in production
math.factorial(n)faster in practicesmallImplemented in C with a smarter algorithm
Counts are in multiplications. Very large factorials have many digits, so each multiplication is itself not truly constant time.

Limits

Stack depth and recursion limits

Python
import sysprint(sys.getrecursionlimit())     # 1000 by defaultdef factorial(n):    if n <= 1:        return 1    return n * factorial(n - 1)print(factorial(300) > 0)          # fine: 300 framestry:    factorial(5000)                # needs 5000 framesexcept RecursionError as e:    print("RecursionError:", e)
See the limit, hit it, and catch it.
Edit and run it in your browser
LanguageTypical limitWhat you see
Python1,000 frames (sys.setrecursionlimit changes it)RecursionError
JavaSet by thread stack size (-Xss), often several thousand framesStackOverflowError
JavaScript (V8)Roughly ten thousand frames, depends on frame sizeRangeError
C / C++OS stack size, often 8 MB on Linux and 1 MB on WindowsSegmentation fault
Exact numbers vary by version, platform and how big each frame is. Plan for depth, not for a specific number.

Comparison

Recursion vs iteration

AspectRecursionIteration
SpaceO(n)O(n) call stack for factorialO(1)O(1) typically
ReadabilityOften cleaner for trees, graphs and nested dataCan be verbose for branching problems
DebuggingHarder: many frames at onceEasier: one context
PerformanceFunction call overhead per stepUsually faster
Best forTrees, graphs, backtracking, divide and conquerSimple loops and large n
Python
import mathdef factorial_iter(n):    result = 1    for i in range(2, n + 1):        result *= i    return resultdef factorial_tail(n, acc=1):    if n <= 1:        return acc    return factorial_tail(n - 1, acc * n)   # tail call: nothing left to do after itprint(factorial_iter(10), factorial_tail(10), math.factorial(10))   # 3628800 x3print(factorial_iter(5000) == math.factorial(5000))                  # True, no recursion
Three ways to compute the same thing. Python does not optimise tail calls, so the tail version still uses O(n) stack.
Edit and run it in your browser

Should I write it recursively?

Factorial is the second kind: perfect for learning recursion, but a loop wins in real code.

Patterns

Kinds of recursion

TypeWhat it meansExamplesTime
LinearOne recursive call per invocationFactorial, sum of an array, reverse a stringO(n)O(n)
Tree (binary)Two or more calls per invocationFibonacci, tree traversalO(2n)O(2^n) naive Fibonacci
TailThe recursive call is the very last operationTail factorial, GCDO(n)O(n); only some languages reuse the frame
Divide and conquerSplit, solve the parts, combineBinary search, merge sort, fast powerVaries: O(log⁡n)O(\log n) to O(nlog⁡n)O(n \log n)
MutualTwo functions call each otheris_even / is_odd, parsersVaries
Divide and conquer is often listed as O(nlog⁡n)O(n \log n). That is merge sort; binary search and fast power are O(log⁡n)O(\log n).

Tree recursion: fib(4) makes 9 calls

fib(2) is computed twice. Factorial's tree is a single chain; Fibonacci's branches, so the call count grows exponentially while the depth stays nn.

Fast power halves the exponent

xn={1n=0(xn/2)2n evenx⋅(x⌊n/2⌋)2n odd⇒O(log⁡n) callsx^n = \begin{cases} 1 & n = 0 \\ \left(x^{n/2}\right)^2 & n \text{ even} \\ x \cdot \left(x^{\lfloor n/2 \rfloor}\right)^2 & n \text{ odd} \end{cases} \quad\Rightarrow\quad O(\log n) \text{ calls}
Compute the half once and square it. 25=2⋅(22)2=322^5 = 2 \cdot (2^2)^2 = 32 takes 4 calls; a million takes about 21.

Pitfalls

Mistakes and how to avoid them

  • Missing or wrong base case

    Define when to stop first, and test the smallest inputs: 0, 1, empty.

  • No progress toward the base

    Every call must shrink the input, for example n - 1 or n // 2.

  • Stack overflow on large input

    Switch to a loop or an explicit stack when depth grows with n.

  • Repeated computation

    Overlapping subproblems need memoization or dynamic programming.

  • Shared state leaking

    Pass copies, or restore state after the recursive call (backtracking).

  • Lost return value

    Write return n * factorial(n - 1), not just the expression.

Debugging a recursion that never ends

Interviews

Interview game plan

Solving any recursive problem

  1. 1

    Base case

    What is the simplest input, and what is its answer?

  2. 2

    Leap of faith

    Assume the recursive call works for a smaller input.

  3. 3

    Combine

    Work out how to use the sub-result to answer the full input.

  4. 4

    Verify small

    Trace n = 2 or n = 3 by hand, then state time and space.

Classic recursion problems to practise

ProblemLevelPattern
FactorialEasyLinear
Fibonacci number (LeetCode 509)EasyTree
Climbing stairs (70)EasyTree, then DP
Reverse linked list (206)EasyLinear
Merge two sorted lists (21)EasyLinear
Maximum depth of binary tree (104)EasyTree
Pow(x, n) (50)MediumDivide and conquer
Generate parentheses (22)MediumBacktracking
Letter combinations of a phone number (17)MediumBacktracking
Permutations (46)MediumBacktracking
Sort an array with merge sort or quick sort (912)MediumDivide and conquer

Analysing a recursive solution

  • Draw the tree

    Sketch the recursion tree to count the calls.

  • Time

    Total nodes × work per node.

  • Space

    Maximum depth of the tree, because that many frames are alive at once.

  • Master Theorem

    For divide and conquer recurrences like T(n)=2T(n/2)+O(n)T(n) = 2T(n/2) + O(n).

Recap

Key takeaways

Key points

  • Recursion solves a problem by calling itself on a smaller copy; every recursive function needs a base case and a recursive case.
  • Factorial: n!=n×(n−1)!n! = n \times (n-1)! with 0!=1!=10! = 1! = 1, so the base case is n <= 1.
  • Calls wind onto the call stack until the base case, then unwind as each frame multiplies and returns.
  • Recursive factorial is O(n)O(n) time and O(n)O(n) stack space; the loop is O(n)O(n) time and O(1)O(1) space.
  • Python stops at about 1,000 frames with RecursionError; raising the limit is risky, a loop is the fix.
  • Python does not optimise tail calls. Tree recursion like Fibonacci needs memoization to avoid exponential time.

Sources