Search

Search papers and lessons

Recursion

Level 2 · 10 min read

Recursion solves a problem by having a function call itself on a smaller version of the problem, stopping at a base case that needs no further calls.

On this page

TL;DR

A recursive function solves a problem by calling itself on a smaller input. Every recursive function needs a base case, an input simple enough to answer directly, so the chain of self-calls ends. Each call reduces the problem a little, and the answers combine on the way back up.

Recursion is often the clearest way to write code for data that is itself nested, such as folders, trees and expressions.

Where you'll see it: in tree traversal (walking every node of a Binary Tree), in divide-and-conquer sorting, in parsers for nested languages such as JSON, and in the recursive definitions that appear throughout mathematics.

Intuition

Nested boxes

Imagine a set of Russian dolls. To find out how many dolls there are in total, you open the outer doll, and the answer is one plus the number of dolls inside it. You do not need to count the whole set at once. You only need to know how to count the dolls inside one doll, and that is the same question again on a smaller set. When you reach the smallest doll, which holds nothing, the answer is simply zero.

That is recursion in one picture. The problem is defined in terms of a smaller copy of itself, and the smallest copy is answered directly.

Why it exists

Many problems have this shape. A folder contains files and other folders. A sentence contains phrases, and phrases contain words. A tree has a root and subtrees, and each subtree is a tree. Writing a loop for such data means tracking your position across nested levels by hand. A recursive function mirrors the structure: it handles the current level, then hands the rest to a call that has the same shape.

The trade is that a recursive function is only as good as its base case and its way of shrinking the problem. A missing or unreachable base case means the calls never stop.

flowchart TD
  A["Call sum on list of 3 items"] --> B{"Is the list empty?"}
  B -- "yes: return 0" --> Z["Answer 0"]
  B -- "no: take first item plus sum of the rest" --> C["Call sum on the remaining items"]
  C --> B

The diagram shows the general pattern. The check on the base case comes first, and the only way forward is a call on a smaller list.

The math

Definition by recursion

A function ff is defined recursively when it is given directly for some inputs (the base cases) and for every other input in terms of ff applied to smaller inputs (the recursive cases). The factorial is the standard example:

f(0)=1,f(n)=n⋅f(n−1)for n≥1.f(0) = 1, \qquad f(n) = n \cdot f(n-1) \quad \text{for } n \ge 1.

Here nn is a whole number, and n!n! (read "n factorial") is the product of the whole numbers from 1 to nn. The first line is the base case. The second is the recursive case, which reduces nn by one each time, so every chain of calls reaches 0.

Why the recursion is correct: induction

To show that a recursive definition or function is right, use proof by induction, the standard method for statements about whole numbers. The argument has two steps:

  1. Base case: show the function returns the right answer for the smallest input.
  2. Inductive step: assume it is right for input kk, and show it is then right for input k+1k + 1, using the recursive case.

For the factorial, f(0)=1=0!f(0) = 1 = 0! is the base. If f(k)=k!f(k) = k!, then f(k+1)=(k+1)⋅f(k)=(k+1)⋅k!=(k+1)!f(k+1) = (k+1) \cdot f(k) = (k+1) \cdot k! = (k+1)!. Both steps hold, so the function is correct for every n≥0n \ge 0.

Cost: the call tree

A recursive computation can be drawn as a tree of calls, where each node is one call and its children are the calls it makes. The total work is roughly the number of nodes. For the naive Fibonacci function, which we define below, the number of calls grows quickly.

The Fibonacci numbers are defined by F0=0F_0 = 0, F1=1F_1 = 1 and Fn=Fn−1+Fn−2F_n = F_{n-1} + F_{n-2}. A naive recursive function that follows this definition makes C(n)C(n) calls, with C(0)=C(1)=1C(0) = C(1) = 1 and C(n)=C(n−1)+C(n−2)+1C(n) = C(n-1) + C(n-2) + 1. Solving this gives C(n)=2Fn+1−1C(n) = 2F_{n+1} - 1. Since Fn+1F_{n+1} grows like φn+1/5\varphi^{n+1}/\sqrt{5}, where φ≈1.618\varphi \approx 1.618, the call count grows exponentially.

024681012140500100015002000nnumber of calls
  • naive Fibonacci calls, approximately
The naive recursive Fibonacci makes about 1.618 times more calls for each extra step in n. The markers are the exact counts for n = 5 and n = 10.

Worked examples

Example
Factorial, step by step

Compute 4!4! with f(0)=1f(0) = 1 and f(n)=n⋅f(n−1)f(n) = n \cdot f(n-1).

  1. f(4)=4⋅f(3)f(4) = 4 \cdot f(3), so we need f(3)f(3).
  2. f(3)=3⋅f(2)f(3) = 3 \cdot f(2), so we need f(2)f(2).
  3. f(2)=2⋅f(1)f(2) = 2 \cdot f(1), so we need f(1)f(1).
  4. f(1)=1⋅f(0)f(1) = 1 \cdot f(0), so we need f(0)f(0).
  5. f(0)=1f(0) = 1 is the base case. No further calls.
  6. Unwind: f(1)=1⋅1=1f(1) = 1 \cdot 1 = 1, f(2)=2⋅1=2f(2) = 2 \cdot 1 = 2, f(3)=3⋅2=6f(3) = 3 \cdot 2 = 6, f(4)=4⋅6=24f(4) = 4 \cdot 6 = 24.

Interpretation: four calls go down, one returns the base answer, and four multiplications come back up. The depth of the call stack is 5 frames, one for each value from 4 down to 0.

Example
Counting the calls for fib(4)

The naive Fibonacci function:

def fib(n):
    if n < 2:
        return n
    return fib(n - 1) + fib(n - 2)

Trace fib(4)\text{fib}(4):

  1. fib(4)\text{fib}(4) calls fib(3)\text{fib}(3) and fib(2)\text{fib}(2).
  2. fib(3)\text{fib}(3) calls fib(2)\text{fib}(2) and fib(1)\text{fib}(1).
  3. The first fib(2)\text{fib}(2) calls fib(1)\text{fib}(1) and fib(0)\text{fib}(0). These are base cases and return 1 and 0, so this fib(2)\text{fib}(2) returns 1.
  4. fib(3)\text{fib}(3) gets fib(1)=1\text{fib}(1) = 1, so it returns 1+1=21 + 1 = 2.
  5. fib(4)\text{fib}(4) now calls fib(2)\text{fib}(2) again. This second call repeats the work of step 3 and returns 1.
  6. fib(4)=2+1=3\text{fib}(4) = 2 + 1 = 3.

Count the calls: the tree has 9 nodes. The formula 2F5−1=2×5−1=92F_5 - 1 = 2 \times 5 - 1 = 9 agrees. The value fib(2)\text{fib}(2) was computed twice, which is the source of the waste.

Example
Summing a list recursively

Define sum([ ])=0\text{sum}([\,]) = 0 and sum([x]+rest)=x+sum(rest)\text{sum}([x] + \text{rest}) = x + \text{sum}(\text{rest}). Compute the sum of [3,1,4][3, 1, 4].

  1. sum([3,1,4])=3+sum([1,4])\text{sum}([3, 1, 4]) = 3 + \text{sum}([1, 4]).
  2. sum([1,4])=1+sum([4])\text{sum}([1, 4]) = 1 + \text{sum}([4]).
  3. sum([4])=4+sum([ ])=4+0=4\text{sum}([4]) = 4 + \text{sum}([\,]) = 4 + 0 = 4.
  4. Unwind: sum([1,4])=1+4=5\text{sum}([1, 4]) = 1 + 4 = 5, then sum([3,1,4])=3+5=8\text{sum}([3, 1, 4]) = 3 + 5 = 8.

Interpretation: each call removes one item from the front and adds it to the answer for the rest. The base case handles the empty list. A loop would do the same job with less overhead, but the recursive version has the same shape as the definition.

Tradeoffs and failure modes

Recursion is clearest when the data is nested. It is risky when the depth is large or when subproblems repeat.

SituationProblemBetter choice
Deeply nested or very long inputEach call adds a stack frame; the program can run out of stack and crashAn explicit loop with your own stack, or tail-call elimination where the language supports it
Same subproblem solved many times (naive Fibonacci)Exponential time from repeated callsMemoisation, which caches each result once, or a bottom-up loop
Simple linear iteration (summing numbers in a range)Overhead for every call and no real gainA plain loop
Tree or graph traversalRecursion mirrors the structure and is easy to readRecursion, or a stack-based loop if the tree is very deep
Missing or unreachable base caseInfinite recursion until the stack overflowsCheck that every call moves towards a base case

Some practical warnings:

  • Python limits the depth. The default recursion limit is about 1000 frames, so a recursive function over a list of 10,000 items fails in CPython without changes. You can raise the limit, but a loop is usually the better fix.
  • Tail calls are not always optimised. A recursive call in tail position (the last thing a function does) can reuse the frame in some languages, but many, including Python, do not do this.
  • Prove the base case first. Most recursion bugs come from a base case that is wrong, missing, or never reached.

History

Recursion is much older than computers. Mathematicians defined functions this way long before programming existed, and the Fibonacci sequence itself was described centuries before the modern notation. In computing, the idea became practical with John McCarthy's Lisp in 1958, which made recursive definitions the main way to write programs. Lisp and the languages that followed showed that a recursive function is easy to reason about, because the induction argument mirrors the code.

Programming languages then had to handle the cost. Implementations store each pending call on a call stack, which is limited in size, so deep recursion can overflow it. Compilers for functional languages began optimising tail calls so that a tail-recursive loop uses constant stack, and this idea spread to other languages that support it.

Recursion caught on because it matches how people define things. A definition that refers to a smaller case is compact, and a program written the same way is usually shorter and easier to check.

Check yourself

QuestionWhat two parts must every correct recursive function have, and what goes wrong if the base case is missing?Show answer

It needs a base case that returns an answer without another call, and a recursive case that calls itself on a smaller input so that the calls eventually reach the base case. If the base case is missing or can never be reached, the calls never stop, and the program eventually fails with a stack overflow.

QuestionCompute 5!5! using f(0)=1f(0) = 1 and f(n)=n⋅f(n−1)f(n) = n \cdot f(n-1). How many multiplications are performed?Show answer

f(1)=1f(1) = 1, f(2)=2f(2) = 2, f(3)=6f(3) = 6, f(4)=24f(4) = 24, and f(5)=5×24=120f(5) = 5 \times 24 = 120. Five multiplications are performed, one for each of n=1n = 1 to n=5n = 5, since f(0)f(0) is a base case that needs none.

QuestionWhy is the naive recursive Fibonacci function so slow, and what is the simplest fix?Show answer

It recomputes the same subproblems many times. Each call to fib(n)\text{fib}(n) makes two more calls, and the subtrees overlap heavily, so the total number of calls grows like φn\varphi^n. Memoisation fixes this by storing each result the first time it is computed, so each value is calculated once and the total work becomes linear in nn.

QuestionYour recursive file-system walker crashes with a stack overflow on one folder, and you know folders there nest only about 50 levels deep. What would you check first, and what would you change if the nesting really were 100,000 levels?Show answer

Fifty levels is far below a typical limit such as Python's default of about 1000 frames, so suspect a bug first: a base case that is never reached, for example a symbolic link that points back to a parent folder and makes the walk loop forever. Fix that by tracking visited folders. If the nesting really were 100,000 levels, rewrite the walk as a loop that keeps an explicit list of folders still to visit. That uses heap memory instead of the call stack, so the depth no longer matters.

Sources