Recursion basics
A function that solves a problem by calling itself on a smaller version of the same problem. Two parts every time: a base case that stops, and a step that shrinks.
How to recognise it
- The problem can be described in terms of a smaller copy of itself (n! is n times (n - 1)!, an array's sum is its first element plus the sum of the rest).
- The input gets smaller in an obvious way each step, such as n becoming n - 1, n becoming n / 10, or an index moving one place.
- The answer is built from the answers to smaller pieces, as later in trees, backtracking and divide and conquer.
- The problem statement asks you to solve it "recursively" or "without loops".
The idea in one picture
You are in a long queue and want to know your position. You can't see the front, so you ask the person ahead of you "what number are you?". They don't know either, so they ask the person ahead of them, and so on. The person at the very front knows they are number 1 without asking anyone. Their answer travels back down the line, each person adding 1, until it reaches you.
That is recursion:
- The base case is the person at the front: a small case you can answer directly, with no further questions.
- The recursive step is everyone else: "my answer is the answer of a smaller problem, plus a little work".
The template
function solve(problem):
if problem is small enough: # base case: answer directly
return the direct answer
smaller = a smaller version of problem
return combine(solve(smaller)) # trust the call, then do your bit
Every recursive function in this pattern is this template with three choices filled in: what counts as "small enough", how to make the problem smaller, and how to combine.
A guided example: the sum of the digits of 4729
Before reading on, answer two questions. What is the smallest number whose digit sum you know immediately? (Any single digit: its digit sum is itself.) How do you get a smaller problem out of 4729? (Drop the last digit: 472.)
So digitSum(n) = n % 10 + digitSum(n / 10), with the base case digitSum(n) = n when n < 10.
| Call | Waits for | Returns |
|---|---|---|
| digitSum(4729) | 9 + digitSum(472) | 9 + 13 = 22 |
| digitSum(472) | 2 + digitSum(47) | 2 + 11 = 13 |
| digitSum(47) | 7 + digitSum(4) | 7 + 4 = 11 |
| digitSum(4) | nothing, it is the base case | 4 |
Read the "Waits for" column from top to bottom: that is the calls going down. Read the "Returns" column from bottom to top: that is the answers coming back up.
Trust the smaller call
When you write n % 10 + digitSum(n / 10), don't try to trace every call in your head. Assume digitSum(n / 10)
already returns the right answer for the smaller number, and only ask: "given that, is my line correct?". If the base
case is right and every step makes the problem smaller, the whole thing is right. This is the same reasoning as a proof by
induction.
The call stack
Every call that is waiting for a smaller call stays open, and each open call holds its own copy of its variables. They
sit on the call stack, last opened first closed. So a recursion that goes n levels deep uses O(n) memory, even with
no arrays at all. The stack has a size limit: Python stops at about 1000 levels by default, and Java and C++ crash with a
stack overflow somewhere in the thousands to hundreds of thousands, depending on the frame size and settings. For a
simple chain of a million steps, use a loop.
When recursion repeats itself
fib(n) = fib(n - 1) + fib(n - 2) is a correct definition, but as code it recomputes the same values over and over.
fib(30) makes about 2.7 million calls to compute a number you could get with 29 additions. When the same smaller problem
appears many times, either remember the answers (memoisation, later in dynamic programming) or build up from the bottom
with a loop. The Fibonacci problem in this pattern shows both.
Common mistakes
- No base case, or a base case the input never reaches (for example, stepping
nby 2 and stopping only atn == 0whennis odd). - A step that does not make the problem smaller, which recurses forever.
- Forgetting to
returnthe recursive result, so the answer is computed and then thrown away. - Recursing thousands of levels deep in Python and hitting the depth limit.
- Using recursion where it repeats work, as in plain Fibonacci.
Problems
- Sum of First N Numberseasyguide ready
- Factorial of a Given Numbereasyguide ready
- Sum of Array Elements IIeasyguide ready
- Check if a Number is Prime or Noteasyguide ready
- Reverse an array 2easyguide ready
- Sum of Digits in a Given Numbereasyguide ready
- Fibonacci Numbereasyguide ready