Skip to content

Chapter 13: Recursion and divide-and-conquer

Correct recursion rests on two things: a base case that stops it, and an input that gets strictly smaller on every call. Divide-and-conquer is the recursive strategy that pushes this furthest. It splits a problem into independent subproblems, solves them recursively, and combines the results. Unlike dynamic programming, the subproblems do not overlap, so there is nothing to memoize; the payoff instead is that splitting often improves the asymptotics, as merge sort’s O(nlog⁡n)O(n \log n) improves on the O(n2)O(n^2) of simple sorts. The Master Theorem tells you exactly when and by how much.

Concepts from other sections (5)

This section uses these ideas. Each has a short definition and a link to the section that explains it in full. Tap a dotted term in the text to preview it.

  • Dynamic programming (DP): solving a problem by breaking it into overlapping subproblems and storing each subproblem’s answer the first time it is computed, which turns an exponential recursion into a polynomial computation. Read more: Chapter 9: Dynamic programming
  • Master theorem: for divide-and-conquer recurrences T(n)=aT(n/b)+f(n)T(n) = aT(n/b) + f(n), comparing f(n)f(n) with nlog⁡ban^{\log_b a} gives T(n)T(n) as Θ(nlog⁡ba)\Theta(n^{\log_b a}), Θ(nlog⁡balog⁡n)\Theta(n^{\log_b a} \log n), or Θ(f(n))\Theta(f(n)), depending on whether the leaves, every level, or the root dominates. Read more: Chapter 12: Discrete Math 2 in Mathematics
  • Quickselect: expected-linear selection of the kk-th element by partitioning, which reorders its input. Read more: 15.4 Heap top-k in C
  • Binary search: a search that keeps an interval known to contain the answer and halves it with one comparison per step, taking O(log⁡n)O(\log n) steps; it needs a monotonic predicate, not necessarily a sorted array. Read more: Chapter 5: Binary search
  • Kadane’s algorithm: the O(n)O(n) maximum-subarray algorithm that tracks the best sum of a subarray ending at the current position, either extending the previous one or starting fresh, along with the best sum seen overall. Read more: Chapter 9: Dynamic programming

This chapter covers the classic split-and-combine template, the merge-sort framework for counting global properties during the merge, quickselect, binary exponentiation, and geometric divide-and-conquer, then states the Master Theorem with worked cases. It ends with two Python examples.

Learning objectives

  • Write a divide-and-conquer recursion with a correct base case, split, and combine step.
  • Count inversions and similar global properties during merge sort’s merge.
  • Find the kkth smallest element in expected O(n)O(n) with quickselect.
  • Compute xnx^n in O(log⁡n)O(\log n) multiplications.
  • Solve recurrences of the form T(n)=aT(n/b)+O(nd)T(n) = aT(n/b) + O(n^d) with the Master Theorem.

You need to be comfortable writing recursive functions and reading big-O notation. Merge sort and binary search, both used here as examples, appear in Binary search; the contrast with overlapping subproblems is developed in Dynamic programming.

Split the range at the midpoint, solve each half, and combine. The base case is a range of one element:

def solve(arr, left, right):
if left == right:
return base_case(arr[left])
mid = (left + right) // 2
left_result = solve(arr, left, mid)
right_result = solve(arr, mid + 1, right)
return combine(left_result, right_result)

Merge Sort, the divide-and-conquer variant of Maximum Subarray, and Count Inversions all follow it. For maximum subarray, the combine step takes the best of the left answer, the right answer, and the best subarray crossing the midpoint, found by extending outward from mid in both directions.

Some problems need a global property that can be computed during the merge step, while both halves are sorted:

def merge_sort(arr):
if len(arr) <= 1:
return arr
mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left, right) # counting happens here

Counting inversions is the model case. During the merge, when right[j] < left[i], every remaining element of left (from i to the end) forms an inversion with right[j], so you add len(left) - i in one step instead of counting pairs individually. Sort an Array, Count of Smaller Numbers After Self, Reverse Pairs, and Count Inversions use this framework.

To find the kkth smallest or largest element without sorting, partition around a random pivot and recurse into only the side that contains the answer:

def quickselect(arr, k):
pivot = arr[random.randint(0, len(arr)-1)]
left = [x for x in arr if x < pivot]
mid = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
if k <= len(left):
return quickselect(left, k)
elif k <= len(left) + len(mid):
return pivot
else:
return quickselect(right, k - len(left) - len(mid))

Because only one side is explored, the expected work is n+n/2+n/4+⋯=O(n)n + n/2 + n/4 + \dots = O(n). Kth Largest Element in an Array, Top K Frequent Elements, and K Closest Points to Origin are the standard problems.

To compute xnx^n, square the half power instead of multiplying nn times, which takes O(log⁡n)O(\log n) multiplications:

def power(x, n):
if n == 0: return 1
if n < 0: return 1 / power(x, -n)
half = power(x, n // 2)
if n % 2 == 0:
return half * half
else:
return half * half * x

The same idea extends to matrix exponentiation (Fibonacci numbers in O(log⁡n)O(\log n)) and to modular exponentiation.

Geometric problems whose brute force is O(n2)O(n^2) often split cleanly in space. The closest pair of points is the classic:

Sort by x-coordinate
Split into left/right halves
Recursively find closest pair in each half
Check strip of width 2*min_dist around midline
Combine results

Only a constant number of points in the strip need to be compared with each point, so the combine step is linear and the whole algorithm is O(nlog⁡n)O(n \log n).

The running time of a divide-and-conquer algorithm that makes aa recursive calls on inputs of size n/bn/b and does O(nd)O(n^d) work to split and combine satisfies

T(n)=a T(n/b)+O(nd).T(n) = a\,T(n/b) + O(n^d).

The answer depends on how dd compares with log⁡ba\log_b a, which measures how fast the number of subproblems grows:

ConditionComplexity
d>log⁡bad > \log_b aO(nd)O(n^d)
d=log⁡bad = \log_b aO(ndlog⁡n)O(n^d \log n)
d<log⁡bad < \log_b aO(nlog⁡ba)O(n^{\log_b a})

Four familiar algorithms show each case:

AlgorithmaabbddResult
merge sort221O(nlog⁡n)O(n \log n)
binary search120O(log⁡n)O(\log n)
Strassen722O(n2.81)O(n^{2.81})
Karatsuba321O(n1.59)O(n^{1.59})

Strassen and Karatsuba both win by reducing aa: seven half-size matrix products instead of eight, three half-size integer products instead of four.

Interviewers favor different variants. As a rough guide:

CompanyFavorite variantDifficulty
Googlecount inversions, closest pairHard
Metaquickselect, merge sort variantsMedium
Jane Streetmatrix exponentiationHard
Two Sigmadivide-and-conquer optimization problemsHard
RenaissanceStrassen-style optimizationsHard
  • Base case: an input on which a recursive function returns directly without calling itself; together with an input that strictly shrinks on every call, it guarantees that the recursion terminates.
  • Divide and conquer / divide-and-conquer: an algorithm design that splits a problem into independent subproblems, solves them recursively, and combines their results; unlike dynamic programming the subproblems do not overlap, and the gain comes from better asymptotics, as in merge sort.
  • Inversion count: the number of pairs i<ji < j with ai>aja_i > a_j, computed in O(nlog⁡n)O(n \log n) during merge sort’s merge by adding the number of remaining left-half elements each time a right-half element is taken first.
  • Binary exponentiation / fast exponentiation: computing xnx^n by squaring x⌊n/2⌋x^{\lfloor n/2 \rfloor} and multiplying by xx once more when nn is odd, in O(log⁡n)O(\log n) multiplications; the same idea gives matrix and modular exponentiation.
  • Closest pair of points: finding the two nearest points in the plane in O(nlog⁡n)O(n \log n) by splitting on xx, solving each half, and checking only a strip around the dividing line, where each point needs comparing with a constant number of others.

Both examples are Python programs; run them with python3 11-recursion-divide-conquer/example-1.py and python3 11-recursion-divide-conquer/example-3.py.

  • Longest monochromatic tree path: an outline, in Python, of a divide-and-conquer solution for the longest path whose nodes all share a color in a rooted tree. divide extends the current path when a node has its parent’s color and restarts it otherwise, recurses into every subtree, and conquer joins the root with its two longest subtree paths (taking only two prevents revisiting nodes). The helper functions are left as stubs to fill in.
  • Maximum circular subarray: the divide-and-conquer maximum subarray, with the crossing-subarray step that extends left and right from the midpoint, applied to every rotation of the array to find the best circular subarray. Trying all nn rotations makes it O(n2log⁡n)O(n^2 \log n); Kadane’s algorithm in Dynamic programming can solve the same problem in O(n)O(n) by also tracking the minimum subarray.