AlgoViz

Recursion: factorial

easy 16 min

Recursion 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)

  1. 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?

  1. Anaasks
  2. Ben
  3. Cai
  4. Dev
  5. Eli
waiting = 1

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"]))   # 5

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Missing base case

    critical

    Without a stopping condition the function calls itself until the stack runs out: RecursionError in Python, a crash in C.

    Wrong
    def factorial(n):    return n * factorial(n - 1)    # never stops
    Right
    def factorial(n):    if n <= 1:        return 1    return n * factorial(n - 1)
  • A base case that can be skipped

    critical

    n == 1 is never reached from n = 0 or from a negative number, so those inputs recurse forever. Use n <= 1 and reject negatives.

    Wrong
    def factorial(n):    if n == 1:        return 1    return n * factorial(n - 1)    # factorial(0) never stops
    Right
    def 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

    critical

    Each call must shrink the problem. Passing the same n, or growing it, means the base case is never reached.

    Wrong
    def factorial(n):    if n <= 1:        return 1    return n * factorial(n)        # same n every time
    Right
    def factorial(n):    if n <= 1:        return 1    return n * factorial(n - 1)    # one step closer
  • Forgetting to return the recursive result

    major

    In Python a function without a return gives None, so the caller ends up multiplying by None and crashes, or the answer is silently lost.

    Wrong
    def factorial(n):    if n <= 1:        return 1    n * factorial(n - 1)           # result thrown away
    Right
    def factorial(n):    if n <= 1:        return 1    return n * factorial(n - 1)
  • Recomputing overlapping subproblems

    major

    Tree recursion like Fibonacci solves the same inputs again and again. Cache results so each input is computed once.

    Wrong
    def fib(n):    if n <= 1:        return n    return fib(n - 1) + fib(n - 2)   # exponential
    Right
    from 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

    minor

    A 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).

    Wrong
    def paths(node, path=[]):          # one list shared by every call    path.append(node)    ...
    Right
    def 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.