Kodewick
Start learning →
Recursion and divide and conquer45 / 50

Recursion and divide and conquer

Lesson 45 of 50 · Part 9 · Algorithm design · about 18 minutes

Recursion hands a problem to a smaller copy of itself, with a base case, a smaller call and a way to combine the answers, so the Tower of Hanoi takes 2ⁿ − 1 moves; divide and conquer cuts a problem into independent parts, as fast power does in O(log n) multiplications.

The Tower of Hanoi with 64 discs, one move a second: how long does it take? 2⁶⁴ − 1 seconds, about 585 billion years. Nobody counted that one by one; it follows from a single sentence: "to move n discs, move the top n − 1 out of the way, move the biggest, then move the n − 1 back on top." That sentence is a recursion. The algorithm design ideas of this chapter (divide and conquer, backtracking, dynamic programming) all start here.

The three parts of a recursion

A recursive function has to make three things clear:

  1. The base case: how small the problem must be to answer straight away, with no further call;
  2. Smaller: hand the problem to a smaller copy of yourself;
  3. Combine: take the smaller problem's answer and work out your own.

The Tower of Hanoi: move n discs from A to C, using B on the way, never putting a big disc on a small one.

  • Base case: just 1 disc, move it from A to C;
  • Smaller: first move the top n − 1 from A to B (using C): a Tower of Hanoi of size n − 1;
  • Combine: move the biggest A → C, then move the n − 1 on B to C (using A).

Draw each call as a node, and the two smaller problems it calls as its children: that's the recursion tree. In the figure, the arrows down are calls, and the dashed arrows up are returns.

3 discs A→C

The recursion tree of hanoi(3, A → C): every call moves exactly one disc itself, and the number under a node is which move that is
main.c
1#include <stdio.h>2 3long moves = 0;4 5void hanoi(int n, char from, char via, char to) {6    if (n == 1) {                         // base case: one disc, just move it7        moves++;8        printf("%c → %c\n", from, to);9        return;10    }11    hanoi(n - 1, from, to, via);          // the top n - 1 out of the way first12    moves++;                              // the biggest one13    printf("%c → %c\n", from, to);14    hanoi(n - 1, via, from, to);          // then the n - 1 back on top15}16 17unsigned long long T(int n) {             // only counting: T(n) = 2T(n - 1) + 118    if (n == 1) return 1;19    return 2 * T(n - 1) + 1;20}21 22int main(void) {23    hanoi(3, 'A', 'B', 'C');24    printf("3 discs: %ld moves\n", moves);25    printf("20 discs: %llu moves\n", T(20));26    printf("64 discs: %llu moves\n", T(64));27    return 0;28}
Output
A → C
A → B
C → B
A → C
B → A
B → C
A → C
3 discs: 7 moves
20 discs: 1048575 moves
64 discs: 18446744073709551615 moves

Why 2ⁿ − 1: let T(n) be the moves for n discs; T(1) = 1 and T(n) = 2T(n − 1) + 1. Each level down the recursion tree has twice as many nodes: 1 + 2 + 4 + … + 2ⁿ⁻¹ = 2ⁿ − 1. One more disc doubles the moves, plus one.

Guess the outputA wrong guess is fine

How many moves for 10 discs?

1#include <stdio.h>2 3long moves = 0;4 5void hanoi(int n, char from, char via, char to) {6    if (n == 1) {7        moves++;8        return;9    }10    hanoi(n - 1, from, to, via);11    moves++;12    hanoi(n - 1, via, from, to);13}14 15int main(void) {16    hanoi(10, 'A', 'B', 'C');17    printf("%ld\n", moves);18    return 0;19}
Choose one

hanoi(3, A → C) takes 7 moves. What is move 4?

Choose one

A recursive function has no way out (or its way out can never be reached). What happens when it runs?

Put in orderDrag, or use the arrows

Put the 3 lines after Hanoi's way out in order, so the program for 2 discs prints the right 3 moves.

  1. printf("%c → %c\n", from, to);
  2. hanoi(n - 1, from, to, via);
  3. hanoi(n - 1, via, from, to);
Should print
A → B
A → C
B → C

Divide and conquer: cut, solve each, combine

Divide and conquer is one way to use recursion: cut the problem into several problems of the same kind that don't depend on each other, solve each recursively, then combine the answers. Chapter 7's merge sort is exactly this:

Merge sortFast power
CutSplit in the middlexⁿ becomes x^(n/2)
Solve eachSort both halves recursivelyWork out x^(n/2) recursively
CombineMerge two sorted halves, O(n)Square it, and times one more x if n is odd
Base caseA single numbern = 0, the answer is 1

Fast power: working out xⁿ the plain way takes n − 1 multiplications. But x¹³ = (x⁶)² × x, x⁶ = (x³)², x³ = (x¹)² × x: n halves each time, so there are only log₂ n levels.

power(3, 13)
1long long power(long long x, int n) {2    calls++;3    if (n == 0) return 1;                     // base case4    long long h = power(x, n / 2);            // worked out once5    h = h * h % MOD;                          // combine: square it6    if (n % 2 == 1) h = h * x % MOD;          // odd: one more x7    return h;8}

power(3, 13): n halves each level, all the way to n = 0; the answers come back up, with one or two multiplications per level
Fill inTap one to fill a blank; tap a blank to take it back

Fast power: fill in the argument of the recursive call so the program prints 1024 2187.

1#include <stdio.h>2 3long long power(long long x, int n) {4    if (n == 0) return 1;5    long long h = power(x, );6    h = h * h;7    if (n % 2 == 1) h = h * x;8    return h;9}10 11int main(void) {12    printf("%lld %lld\n", power(2, 10), power(3, 7));13    return 0;14}
Exercise 1

A maximum by divide and conquer

Find the maximum of a[lo..hi] by divide and conquer: a single number is its own maximum; otherwise split in the middle, find each half's maximum, and return the bigger.

It should print
9 -3
exercise1.c
1#include <stdio.h>2 3int max_of(int a[], int lo, int hi) {4    // base case: lo == hi; otherwise mid = (lo + hi) / 2, recurse on both halves, return the bigger5    return a[lo];6}7 8int main(void) {9    int a[] = {3, 9, 2, 7, 5, 8, 1};10    int b[] = {-4, -8, -3, -6};11    printf("%d %d\n", max_of(a, 0, 6), max_of(b, 0, 3));12    return 0;13}
Output
Press Run or Ctrl+Enter

Don't solve the same subproblem twice

Fast power is fast because power(x, n / 2) is worked out once, kept in h, and multiplied by itself. Write it twice in the same expression and the result is the same, but the cost is completely different. This step's program puts the right power next to the wrong power_bad (which writes power(x, n / 2) twice) and compares how many calls each makes. The results soon overflow long long, so both are taken modulo 1000000007 (the usual way in exams and interviews).

main.c
1#include <stdio.h>2 3#define MOD 10000000074long calls;5 6long long power(long long x, int n) {7    calls++;8    if (n == 0) return 1;                     // base case9    long long h = power(x, n / 2);            // worked out once10    h = h * h % MOD;                          // combine: square it11    if (n % 2 == 1) h = h * x % MOD;          // odd: one more x12    return h;13}14 15long long power_bad(long long x, int n) {16    calls++;17    if (n == 0) return 1;18    long long h = power_bad(x, n / 2) * power_bad(x, n / 2) % MOD;   // worked out twice19    if (n % 2 == 1) h = h * x % MOD;20    return h;21}22 23int main(void) {24    int ns[] = {10, 1000, 50000};25    for (int i = 0; i < 3; i++) {26        calls = 0;27        long long a = power(3, ns[i]);28        long good = calls;29        calls = 0;30        long long b = power_bad(3, ns[i]);31        printf("n = %-5d result %lld / %lld   calls: %ld vs %ld\n", ns[i], a, b, good, calls);32    }33    return 0;34}
Output
n = 10    result 59049 / 59049   calls: 5 vs 31
n = 1000  result 56888193 / 56888193   calls: 11 vs 2047
n = 50000 result 878110356 / 878110356   calls: 17 vs 131071

Same results, wildly different numbers of calls. At n = 50000 the right version makes 17 calls and the wrong one over 130,000, slower than multiplying 50,000 times the plain way. The only difference is one line: the same smaller problem worked out twice.

n=4

power_bad(x, 4): every call works out the same smaller problem twice, so each level of the tree doubles: 15 calls in all
Guess the outputA wrong guess is fine

How many times is power_bad called in all for power_bad(2, 8)?

1#include <stdio.h>2 3long calls = 0;4 5long long power_bad(long long x, int n) {6    calls++;7    if (n == 0) return 1;8    long long h = power_bad(x, n / 2) * power_bad(x, n / 2);9    if (n % 2 == 1) h = h * x;10    return h;11}12 13int main(void) {14    power_bad(2, 8);15    printf("%ld\n", calls);16    return 0;17}
Choose one

How do you fix power_bad?

Exercise 2

Fast power modulo m

Complete power(x, n, m) to work out xⁿ % m, calling itself only once.

It should print
1024 73741817 916902199
exercise2.c
1#include <stdio.h>2 3long long power(long long x, int n, long long m) {4    // n == 0 returns 1; h = power(x, n / 2, m); h = h * h % m; one more x if n is odd5    return 1;6}7 8int main(void) {9    printf("%lld %lld %lld\n", power(2, 10, 1000000007), power(2, 30, 1000000007), power(3, 100000, 1000000007));10    return 0;11}
Output
Press Run or Ctrl+Enter

The cost: levels × work per level

You can estimate a recursion's cost straight from its tree: how many levels, how much work on each level in all, multiplied (added up when the levels differ). That's the idea behind the "master theorem", and it gets the common cases right with no formula to learn:

RecurrenceExampleLevelsWork per levelIn all
T(n) = T(n/2) + 1Binary search, fast powerlog n1O(log n)
T(n) = 2T(n/2) + nMerge sortlog nn (all the pieces on a level add up to n numbers)O(n log n)
T(n) = 2T(n/2) + 1power_bad, an array's maximum by divide and conquerlog n1, 2, 4… n on the lastO(n)
T(n) = 2T(n − 1) + 1Tower of Hanoin1, 2, 4… 2ⁿ⁻¹O(2ⁿ)
T(n) = T(n − 1) + nRecursive selection sortnn, n − 1, …O(n²)

Looking at a recursion, ask two things first: how many smaller problems each call makes (how wide the tree is), and how much smaller they get (how deep: halving is log n levels, minus one is n levels). Halving or minus one is the difference between log n and n; working the same smaller problem out once or twice is the difference between log n and n, or even n and 2ⁿ.

Recursion has one more cost: each level of calls takes a stack frame. A depth of log n is fine; a depth of n (walking a linked list of a million nodes recursively, say) can overflow the stack, and then it should become a loop.

main()power(3, 13)

The call stack during power(3, 13): it goes down one path at a time, with at most 5 calls of power piled up; each return takes one off

In exams: "how many moves for n discs in the Tower of Hanoi" (2ⁿ − 1); "write the recurrence and give the time complexity", like T(n) = 2T(n/2) + n giving O(n log n); "which structure does recursion use" (a stack); "the space complexity of a recursive algorithm" depends on the deepest the recursion goes, not on the total number of calls.

Choose one

What is the time complexity of summing an array by divide and conquer?

1int sum(int a[], int lo, int hi) {2    if (lo == hi) return a[lo];3    int mid = (lo + hi) / 2;4    return sum(a, lo, mid) + sum(a, mid + 1, hi);5}
Choose one

hanoi(n) makes 2ⁿ − 1 calls in all. What is its space complexity (the deepest the call stack gets)?

Summary

Take-away

Recursion and divide and conquer

  • Three parts: a base case, hand it to a smaller self, combine the answers
  • Tower of Hanoi: T(n) = 2T(n − 1) + 1, 2ⁿ − 1 moves
  • Divide and conquer: cut into independent parts, solve each, combine (merge sort, fast power)
  • Cost = the recursion tree's levels × the work per level; never work the same part out twice
1long long power(long long x, int n) {2    if (n == 0) return 1;3    long long h = power(x, n / 2);4    return n % 2 ? h * h * x : h * h;5}