Recursion: factorial
easy 16 minRecursion is a function solving a problem by calling itself on a smaller copy of it.
See it run
Watch factorial calls pile up on the call stack, hit the base case and unwind, then compare the loop, the recursion limit and five other recursion patterns.
Operations
factorial(4) on the call stack
Each call pushes a frame and waits for the smaller call; the base case stops the descent and the answers multiply on the way back up.
Step 1 of 10
Call factorial(4)
- factorial(4)TOP
depth 1
The program calls factorial(4). A stack frame is pushed holding n = 4 and the place to return to. The stack has 1 frame.
Step 1: Call factorial(4)
def factorial(n): if n <= 1: # base case return 1 return n * factorial(n - 1) # recursive caseprint(factorial(4)) # 24- Time
- O(n)
- Space
- O(n)
- frames at the deepest point
- 4 for n = 4
- multiplications
- 3 (n - 1)
Read the stack as a to-do list: each frame below the top is a multiplication waiting for one number.
In the real world
The same recursion: factorial doing real jobs. Pick one and step through it.
Nobody can see the whole line, so each person asks the one behind and adds 1 to the answer.
Step 1 of 5
How many people are in the line?
- Anaasks
- Ben
- Cai
- Dev
- Eli
You are at the front of a line and someone asks how long it is. You cannot see the end. Instead of counting everyone, you say: I am 1, plus however many are behind me, and pass the question back.
Step 1: How many people are in the line?
def count(line, i=0): if i == len(line) - 1: # last person: nobody behind me return 1 return 1 + count(line, i + 1) # me plus everyone behind meprint(count(["Ana", "Ben", "Cai", "Dev", "Eli"])) # 5Common mistakes
The bugs interviewers watch for, with the fix beside each.
Missing base case
criticalWithout a stopping condition the function calls itself until the stack runs out: RecursionError in Python, a crash in C.
Wrongdef factorial(n): return n * factorial(n - 1) # never stopsRightdef factorial(n): if n <= 1: return 1 return n * factorial(n - 1)A base case that can be skipped
criticaln == 1 is never reached from n = 0 or from a negative number, so those inputs recurse forever. Use n <= 1 and reject negatives.
Wrongdef factorial(n): if n == 1: return 1 return n * factorial(n - 1) # factorial(0) never stopsRightdef factorial(n): if n < 0: raise ValueError("n must be >= 0") if n <= 1: return 1 return n * factorial(n - 1)Not moving toward the base case
criticalEach call must shrink the problem. Passing the same n, or growing it, means the base case is never reached.
Wrongdef factorial(n): if n <= 1: return 1 return n * factorial(n) # same n every timeRightdef factorial(n): if n <= 1: return 1 return n * factorial(n - 1) # one step closerForgetting to return the recursive result
majorIn Python a function without a return gives None, so the caller ends up multiplying by None and crashes, or the answer is silently lost.
Wrongdef factorial(n): if n <= 1: return 1 n * factorial(n - 1) # result thrown awayRightdef factorial(n): if n <= 1: return 1 return n * factorial(n - 1)Recomputing overlapping subproblems
majorTree recursion like Fibonacci solves the same inputs again and again. Cache results so each input is computed once.
Wrongdef fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2) # exponentialRightfrom functools import lru_cache@lru_cache(maxsize=None)def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2) # O(n)Sharing mutable state across calls
minorA mutable default argument or a list that is changed and not restored leaks between calls. Pass copies, or undo the change after the recursive call (backtracking).
Wrongdef paths(node, path=[]): # one list shared by every call path.append(node) ...Rightdef paths(node, path=None): path = [] if path is None else path path.append(node) ... path.pop() # restore before returning
Interview tips
How to solve a recursive problem
- Start with the base case: what is the smallest input, and what is its answer?
- Take the leap of faith: assume the recursive call already works for a smaller input.
- Work out how to turn that sub-result into the answer for the full input.
- Verify by hand on a small example such as n = 2 or n = 3.
Analysing complexity
- Draw the recursion tree to count the calls.
- Time = number of nodes × work per node.
- Space = the maximum depth of the tree, since that many frames are alive at once.
- Use the Master Theorem for divide and conquer recurrences.
Memory tricks
- BRAT: Base case first, Return a value, Approach the base, Trust the recursive call.
- Russian dolls: open smaller and smaller until the solid doll, then close them in reverse.
- The line of people: I am 1 plus however many are behind me.
Say this in the interview
- Name the base case and the recursive case out loud before writing code.
- State time and space, and point out that the stack is the space.
- Offer the iterative version when the depth could be large, and mention Python's limit of about 1,000 frames.
- Mention that Python does not optimise tail calls, so tail recursion does not save stack there.