Recursion: factorial
easy 16 minRecursion 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
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.
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
The recursive form
| n | n! as a smaller factorial | Value |
|---|---|---|
| 0 | base case | 1 |
| 1 | base case | 1 |
| 3 | 6 | |
| 4 | 24 | |
| 5 | 120 | |
| 6 | 720 |
Anatomy
Base case and recursive case
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)) # 1One call of factorial(n), step by step
A correct base case
- Is checked before any recursive call.
- Is reachable from every valid input:
n <= 1catches both 0 and 1. - Returns the right value: , not 0.
A broken recursion
- Has no base case, so it never stops.
- Uses
n == 1, whichfactorial(0)jumps straight past. - Calls
factorial(n)instead offactorial(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
What each frame holds (inside factorial(3))
| Frame | Parameter | Waiting for | Will compute |
|---|---|---|---|
| factorial(3) | n = 3 | factorial(2) | result |
| factorial(2) | n = 2 | factorial(1) | result |
| factorial(1) | n = 1 | nothing: base case | returns 1 |
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
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)Complexity
Time and space
Time: one call per value of n
Space: the deepest the stack gets
| Version | Time | Extra space | Note |
|---|---|---|---|
Recursive factorial(n) | stack | Hits the recursion limit for large n | |
| Iterative loop | The default choice in production | ||
math.factorial(n) | faster in practice | small | Implemented in C with a smarter algorithm |
Limits
Stack depth and recursion limits
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)| Language | Typical limit | What you see |
|---|---|---|
| Python | 1,000 frames (sys.setrecursionlimit changes it) | RecursionError |
| Java | Set by thread stack size (-Xss), often several thousand frames | StackOverflowError |
| JavaScript (V8) | Roughly ten thousand frames, depends on frame size | RangeError |
| C / C++ | OS stack size, often 8 MB on Linux and 1 MB on Windows | Segmentation fault |
Comparison
Recursion vs iteration
| Aspect | Recursion | Iteration |
|---|---|---|
| Space | call stack for factorial | typically |
| Readability | Often cleaner for trees, graphs and nested data | Can be verbose for branching problems |
| Debugging | Harder: many frames at once | Easier: one context |
| Performance | Function call overhead per step | Usually faster |
| Best for | Trees, graphs, backtracking, divide and conquer | Simple loops and large n |
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 recursionShould I write it recursively?
Patterns
Kinds of recursion
| Type | What it means | Examples | Time |
|---|---|---|---|
| Linear | One recursive call per invocation | Factorial, sum of an array, reverse a string | |
| Tree (binary) | Two or more calls per invocation | Fibonacci, tree traversal | naive Fibonacci |
| Tail | The recursive call is the very last operation | Tail factorial, GCD | ; only some languages reuse the frame |
| Divide and conquer | Split, solve the parts, combine | Binary search, merge sort, fast power | Varies: to |
| Mutual | Two functions call each other | is_even / is_odd, parsers | Varies |
Tree recursion: fib(4) makes 9 calls
Fast power halves the exponent
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 - 1orn // 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
Base case
What is the simplest input, and what is its answer?
- 2
Leap of faith
Assume the recursive call works for a smaller input.
- 3
Combine
Work out how to use the sub-result to answer the full input.
- 4
Verify small
Trace n = 2 or n = 3 by hand, then state time and space.
Classic recursion problems to practise
| Problem | Level | Pattern |
|---|---|---|
| Factorial | Easy | Linear |
| Fibonacci number (LeetCode 509) | Easy | Tree |
| Climbing stairs (70) | Easy | Tree, then DP |
| Reverse linked list (206) | Easy | Linear |
| Merge two sorted lists (21) | Easy | Linear |
| Maximum depth of binary tree (104) | Easy | Tree |
| Pow(x, n) (50) | Medium | Divide and conquer |
| Generate parentheses (22) | Medium | Backtracking |
| Letter combinations of a phone number (17) | Medium | Backtracking |
| Permutations (46) | Medium | Backtracking |
| Sort an array with merge sort or quick sort (912) | Medium | Divide 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 .
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: with , 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 time and stack space; the loop is time and 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.