Recursion and divide and conquer
Recursion hands a problem to a smaller copy of itself and needs a base case, a way to shrink and a way to combine; computing 3 to the 4000th by halving takes 13 calls, and divide and conquer splits a problem into parts, solves each and combines them.
Work out 3 to the power 4000, modulo 1000000007. Multiplying it out takes 3999 multiplications. Think of it differently: "3⁴⁰⁰⁰ is 3²⁰⁰⁰ times itself", and 3²⁰⁰⁰ is 3¹⁰⁰⁰ times itself… n halves each time, and 13 calls finish the job. That sentence is recursion: hand the problem to a smaller copy of yourself. Yet it is still recursion if you write "compute it twice" instead of "compute it once and keep it", and then it takes 8191 calls. This lesson looks closely at how recursion is written and what it costs, then at divide and conquer: cut the problem into parts, solve each, put them together. Backtracking and dynamic programming, later in this chapter, both start from here.
The base case and the smaller problem
A recursive function must say three things:
- The base case: how small is small enough to answer directly, without calling itself;
- The smaller problem: hand a smaller version to itself;
- Combine: from the smaller answer, work out its own.
The sum of a list: total(nums, i) adds from index i to the end. The base case is i == len(nums), no numbers left, sum 0; otherwise it is nums[i] plus "the sum from i + 1 on".
Each call pushes a new frame on Python's call stack, holding that call's own i; a return pops it and hands the answer to the frame below.
<module>s = ?total(i=0)nums[0] = 5total(i=1)nums[1] = 3total(i=2)nums[2] = 8total(i=3)base case1def total(nums, i=0):2 if i == len(nums): # base case3 return 04 return nums[i] + total(nums, i + 1) # smaller problem + combine5 6def total_no_base(nums, i=0):7 return nums[i] + total_no_base(nums, i + 1) # forgot the base case8 9print(total([5, 3, 8]))10print(total(list(range(1, 101))))11try:12 total_no_base([5, 3, 8])13except IndexError:14 print("no base case: i runs up to 3, and nums[3] is out of range")15 16def count_down(n):17 if n == 0:18 return 019 return count_down(n - 1)20 21try:22 count_down(100000)23except RecursionError:24 print("100000 levels of recursion: RecursionError")
16 5050 no base case: i runs up to 3, and nums[3] is out of range 100000 levels of recursion: RecursionError
Both mistakes are common. With no base case the recursion never stops; here it hit an index error first, and with nothing else to stop it, it piles up until the stack is full. Too deep fails the same way even with a correct base case: Python's call stack holds about a thousand frames by default, and count_down(100000) raises RecursionError long before it gets there. The extra space recursion uses is its greatest depth, not its total number of calls: total uses O(n).
A recursive function is missing its base case, and no other error turns up first. What happens when Python runs it?
RecursionError instead of hanging. A correct base case can hit it too if the recursion goes too deep.Put the 3 lines of total in order so the program prints 16 0.
return 0if i == len(nums):return nums[i] + total(nums, i + 1)
16 0
return nums[i] + ... came first, total([]) would read nums[0] on its very first step and fail with an index error, never reaching the base case.Flatten a nested list
✓Complete flatten(items): each item is either a number or a list (and lists can hold more lists). Return all the numbers, left to right, in one list.
[1, 2, 3, 4, 5] [6, 7, 8] []
1def flatten(items):2 out = []3 for x in items:4 # x is a list: add the result of flatten(x) to out; otherwise put x in out5 pass6 return out7 8print(flatten([1, [2, [3, 4]], 5]))9print(flatten([[[]], [6], [[7, [8]]]]))10print(flatten([]))
The recursion tree: counting calls
Fibonacci numbers: fib(0) = 0, fib(1) = 1, and each one after is the sum of the two before. Written straight from the definition, it is three lines:
1def fib(n):2 if n < 2:3 return n4 return fib(n - 1) + fib(n - 2)5 6print([fib(n) for n in range(10)])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Each call calls itself twice. Draw each call as a node and the calls it makes as its children, and you get the recursion tree. The arrows down are calls, and the dashed arrows up are returns:
1def fib(n):2 if n < 2:3 return n4 return fib(n - 1) + fib(n - 2)
How fast do the calls grow? Add a counter and take n from 5 to 20.
1calls = 02 3def fib(n):4 global calls5 calls += 16 if n < 2:7 return n8 return fib(n - 1) + fib(n - 2)9 10for n in [5, 10, 15]:11 calls = 012 value = fib(n)13 print(f"fib({n}) = {value}, {calls} calls")
fib(5) = 5, 15 calls fib(10) = 55, 177 calls fib(15) = 610, 1973 calls
Each time n grows by 5, the calls multiply by about 11: the count is exactly 2 × fib(n + 1) − 1, growing like fib itself, 1.618ⁿ, exponentially. fib(40) makes over 330 million calls. The figure shows why: the same small problem is worked out from scratch again and again. Dynamic programming, two lessons on, deals with exactly this; for now remember: to see whether a recursion is fast, count the nodes on its recursion tree.
How many calls to fib does fib(6) make, counting the first one?
1calls = 02 3def fib(n):4 global calls5 calls += 16 if n < 2:7 return n8 return fib(n - 1) + fib(n - 2)9 10fib(6)11print(calls)
Each call calls itself twice, and the size only drops by 1. How many calls does f(4) make in all?
1calls = 02 3def f(n):4 global calls5 calls += 16 if n <= 1:7 return8 f(n - 1)9 f(n - 1)10 11f(4)12print(calls)
Fast power: halve each time
To compute xⁿ, x * x * … * x takes n − 1 multiplications. As a recursion:
- base case: n = 0, the answer is 1;
- smaller problem: first find h = x^(n // 2);
- combine: if n is even the answer is h × h; if odd, times one more x.
n halves at each level, so the recursion tree is just a chain, log₂ n levels deep:
Python's integers never overflow, but 3⁴⁰⁰⁰ already has more than 1900 digits, and each multiplication gets slower. Problems and interviews usually ask for the answer modulo 1000000007, reduced after every multiplication, so the numbers never go above 10⁹. Alongside it is a wrong version: it writes power(x, n // 2) twice instead of computing it once and keeping it.
1MOD = 1_000_000_0072calls = 03 4def power(x, n):5 global calls6 calls += 17 if n == 0: # base case8 return 19 half = power(x, n // 2) # smaller problem: computed once10 result = half * half % MOD # combine11 if n % 2 == 1:12 result = result * x % MOD13 return result14 15def power_bad(x, n):16 global calls17 calls += 118 if n == 0:19 return 120 result = power_bad(x, n // 2) * power_bad(x, n // 2) % MOD # the same subproblem twice21 if n % 2 == 1:22 result = result * x % MOD23 return result24 25for n in [10, 1000, 4000]:26 calls = 027 a = power(3, n)28 good = calls29 calls = 030 b = power_bad(3, n)31 print(f"n = {n:<6} {a} {b} calls {good} vs {calls}")32print(pow(3, 4000, MOD))
n = 10 59049 59049 calls 5 vs 31 n = 1000 56888193 56888193 calls 11 vs 2047 n = 4000 824206305 824206305 calls 13 vs 8191 824206305
The same results, wildly different call counts: at n = 4000 the right version makes 13 calls and the wrong one 8191, more than multiplying it out 4000 times. The only difference is one line: the same subproblem computed twice turns the recursion tree from a chain into a full binary tree, doubling at every level. The last line is Python's built-in pow(x, n, mod): the same halving, written in C. At work, use it.
power_bad writes power_bad(x, n // 2) twice. What result and call count does it print?
1calls = 02 3def power_bad(x, n):4 global calls5 calls += 16 if n == 0:7 return 18 result = power_bad(x, n // 2) * power_bad(x, n // 2)9 if n % 2 == 1:10 result = result * x11 return result12 13print(power_bad(2, 8), calls)
Fast power: fill in the argument of the recursive call so the program shows 1024 2187.
1def power(x, n):2 if n == 0:3 return 14 half = power(x, )5 result = half * half6 if n % 2 == 1:7 result = result * x8 return result9 10print(power(2, 10), power(3, 7))
n - 1 takes off just one each time, and half * half comes out wrong too; n / 2 gives a fraction that never reaches n == 0, ending in RecursionError; n goes round in circles.Fast power, modulo m
✓Complete my_pow(x, n, m) to compute xⁿ % m. It may call itself only once, and its results must match the built-in pow(x, n, m).
1024 73741817 883496652 True 1
1def my_pow(x, n, m):2 # base case: n == 0 returns 1 % m3 # half = my_pow(x, n // 2, m); half * half % m; times x again if n is odd4 return 15 6M = 1_000_000_0077print(my_pow(2, 10, M), my_pow(2, 30, M), my_pow(3, 20000, M))8print(my_pow(3, 20000, M) == pow(3, 20000, M), my_pow(5, 0, 7))
Divide and conquer: split, solve, combine
Divide and conquer is one way of using recursion: cut the problem into several smaller problems of the same kind that do not depend on each other, solve each recursively, and combine their answers. The simplest example: the maximum of a list is the larger of the left half's maximum and the right half's maximum.
Divide and conquer is no faster for the maximum: one scan also takes n − 1 comparisons. It pays off when the combine step can use what each half already worked out. Merge sort, from chapter 7, does: both halves come back sorted, so merging takes only O(n). The merge can also count inversions (pairs with i < j but a[i] > a[j], a measure of how unsorted a list is): when the right side's right[j] goes down first, the len(left) - i numbers left on the left are all larger, and each forms an inversion with it.
1comparisons = 02 3def count_brute(a): # compare every pair: n(n - 1)/2 of them4 global comparisons5 inv = 06 for i in range(len(a)):7 for j in range(i + 1, len(a)):8 comparisons += 19 if a[i] > a[j]:10 inv += 111 return inv12 13def sort_count(a): # returns (the sorted list, the number of inversions)14 global comparisons15 if len(a) <= 1:16 return a, 017 mid = len(a) // 218 left, x = sort_count(a[:mid])19 right, y = sort_count(a[mid:])20 merged, cross = [], 021 i = j = 022 while i < len(left) and j < len(right):23 comparisons += 124 if left[i] <= right[j]:25 merged.append(left[i])26 i += 127 else:28 merged.append(right[j])29 j += 130 cross += len(left) - i # everything left on the left is bigger than right[j]31 merged += left[i:] + right[j:]32 return merged, x + y + cross33 34print(sort_count([3, 1, 4, 2]))35a = [(i * 37) % 400 for i in range(400)]36comparisons = 037print("every pair:", count_brute(a), "inversions,", comparisons, "comparisons")38comparisons = 039print("while merging:", sort_count(a)[1], "inversions,", comparisons, "comparisons")
([1, 2, 3, 4], 3) every pair: 38748 inversions, 79800 comparisons while merging: 38748 inversions, 2827 comparisons
With 400 numbers the answer is the same and the comparisons drop from 79800 to 2827: O(n²) against O(n log n).
An inversion is a pair with i < j but a[i] > a[j]. How many inversions does [4, 3, 1, 2] have?
The cost: levels × work per level
You can estimate a recursion's cost straight from its tree: how many levels, how much work across each level, multiplied (added up when levels differ).
| Recurrence | Example | Levels | Work per level | Total |
|---|---|---|---|---|
| T(n) = T(n/2) + 1 | fast power, binary search | log n | 1 | O(log n) |
| T(n) = 2T(n/2) + n | merge sort, counting inversions | log n | n (all the pieces of a level add up to n) | O(n log n) |
| T(n) = 2T(n/2) + 1 | maximum by halves, power_bad | log n | 1, 2, 4… n on the last | O(n) |
| T(n) = T(n − 1) + 1 | total(nums, i) | n | 1 | O(n) |
| T(n) = T(n − 1) + T(n − 2) + 1 | naive fib | n | more and more further down | O(1.618ⁿ) |
Faced with a recursion, ask two things first: how many subproblems does each call make (how wide the tree is), and how much smaller do they get (how deep it is: halving gives log n levels, minus one gives n).
In interviews: "write the recurrence and give the complexity": T(n) = 2T(n/2) + n is O(n log n). "The space complexity of a recursion" is its greatest depth (O(log n) for fast power, O(n) for total), not its total number of calls. "Write fast power": keep half in a variable so it recurses only once.
What is the time complexity of summing an array by divide and conquer?
1def total(a, lo, hi):2 if lo == hi:3 return a[lo]4 mid = (lo + hi) // 25 return total(a, lo, mid) + total(a, mid + 1, hi)
power(x, n) recurses only once per call and halves n. What is its space complexity (the call stack at its deepest)?
total(nums, i) only drops by 1 per level, so its depth is n and it is O(n).How you write it at work
1MOD = 1_000_000_0072print(pow(2, 10), pow(2, 10, 1000))3print(pow(3, 20000, MOD))4print(len(str(3 ** 2000)), "digits")5 6nums = [3, 9, 2, 7]7print(sum(nums), max(nums))8 9def total_slice(nums):10 if not nums:11 return 012 return nums[0] + total_slice(nums[1:]) # every level copies a slice13print(total_slice(nums))
1024 24 883496652 955 digits 21 9 21
- For a power modulo something, use the built-in
pow(x, n, mod)rather than writing your own; without a modulus,x ** nis an exact big integer, and for large n it gets very long. - For a sum, a maximum or a minimum, use
sum,max,min: one scan, no recursion. nums[0] + total_slice(nums[1:])looks neat, but every level's slice copies n − 1 items, O(n²) in all. When a recursion needs "the rest", pass an index i instead of slicing.- Python recursion goes only about a thousand levels deep: when the depth grows with the data (a linked list's length, a list's length), use a loop or an explicit stack. Depth log n (fast power, merge sort, a balanced tree) is safe.
- Repeated subproblems can be remembered by
functools.lru_cache: lesson 4 is all about it.
total_slice(nums) writes nums[1:] on every level. For a sum of n numbers, what is the total time?
Summary
Recursion and divide and conquer
- Three things: a base case, a smaller copy of the problem, combining the answers
- Speed: count the recursion tree's nodes; space: its greatest depth; Python allows about a thousand
- Naive fib calls itself twice per call, exponential; fast power once, O(log n)
- Divide and conquer: independent parts, each solved, then combined (merge sort, inversions)
- Cost = levels × work per level; never compute the same subproblem twice
1def power(x, n):2 if n == 0:3 return 14 half = power(x, n // 2)5 return half * half * (x if n % 2 else 1)6pow(x, n, 1_000_000_007)