BeginnerRecursion

Recursion: a base case and a smaller problem

A function handles one step and hands the rest to a smaller copy of itself, until a answers directly.

The idea

Every recursive function needs two parts: a base case that answers without calling itself, and a step that makes the input smaller and calls itself on what's left.

Trust the call. Assume total(rest) already returns the right answer, and only work out how to combine it with the current item. Each call waits on the until the one below it returns.

Worked example

total([2, 5, 1])

  1. total([2, 5, 1]) = 2 + total([5, 1])
  2. total([5, 1]) = 5 + total([1])
  3. total([1]) = 1 + total([]), and total([]) = 0 is the base case
  4. Unwinding: 1 + 0 = 1, then 5 + 1 = 6, then 2 + 6 = 8

Pseudocode

The steps in plain words. ← means “set to”; indentation shows what's inside what.

factorial(n):
if n = 0: return 1(base case: stops the calls)
return n × factorial(n − 1)(a smaller copy of the problem)

See it run

The worked example, step by step, beside the Python. The highlighted line is the one running.

Step-by-step

n = 3

call stack

empty

Solution · Python

def total(nums, i=0):
if i == len(nums): # base case: nothing left
return 0
return nums[i] + total(nums, i + 1)
def power(x, n): # halve n each call: O(log n)
if n == 0:
return 1
half = power(x, n // 2)
return half * half if n % 2 == 0 else half * half * x

Step 1 of 9

A recursive function solves a smaller copy of the problem, then finishes its own part. Each waiting call sits on the call stack.

total: time and O(n) call stack. power: , since each call halves n.

How to spot it

  • The answer is defined by a smaller copy of the same problem: n − 1, n / 2, the rest of a list, a .
  • Nested structures: brackets inside brackets, folders inside folders.

Common mistakes

  • A missing base case, or one the input never reaches: the calls never stop and the overflows.
  • Python stops at about 1,000 nested calls by default: for long inputs, use a loop instead.

Practise the ideas first

Practise it

Go further