AlgoViz

Recursion: factorial

easy 16 min

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

Remember it

The few things worth knowing cold, and how to make them stick.

Memory hook

Base case first, then a smaller copy: n! is n times (n-1)!, down to 1.

Russian dolls. Each doll opens to reveal a smaller doll, until you reach the smallest solid doll that does not open: the base case. Then you close them back up in reverse order, smallest first, just like frames unwinding off the call stack.

Cheat sheet

Base case
n <= 1 returns 1
Recursive case
n * factorial(n - 1)
0! and 1!
both 1
Time
O(n)
Stack space
O(n), depth n
Loop version
O(n) time, O(1) space
Python limit
about 1000 frames, RecursionError
Tail calls in Python
not optimised
Naive Fibonacci
exponential, memoize it

Spot it when you see

  • The definition refers to itself: n! uses (n-1)!.
  • Nested data: folders in folders, lists in lists, trees, JSON.
  • Split, solve the halves, combine: divide and conquer.
  • Try every choice and undo it: backtracking, permutations, subsets.
  • A problem that is easy for size 0 or 1 and builds up from smaller sizes.

Tricks that stick

  • BRAT: Base case first, Return a value, Approach the base, Trust the recursive call.
  • Russian dolls: open smaller dolls until the solid one, then close them in reverse.
  • The line of people: I am 1 plus however many are behind me.
  • Wind down, unwind up: calls pile up to the base case, answers bubble back.
  • Space equals depth: count the frames alive at the base case.

Do not forget

  • No base case, or one that some inputs skip, such as n == 1 for n = 0.
  • Calling with the same argument, so the problem never shrinks.
  • Forgetting return on the recursive line, so the result becomes None.
  • Deep inputs hitting Python's limit of about 1000 frames.
  • Assuming tail recursion saves stack in Python.
  • Recomputing the same subproblems in tree recursion without a cache.