Divide and conquer solves a problem by splitting it into smaller instances of the same problem, solving those recursively, and combining their answers. It powers merge sort, quick sort, binary search, fast multiplication and many geometric algorithms. Its running time is described by a recurrence, and the Master Theorem turns most of those recurrences into a Big-O answer in one line.
Think of it like
Grading a stack of exams with teaching assistants
A professor with 400 exams hands 200 each to two assistants, who each hand 100 to two helpers, and so on until everyone holds a handful they can grade directly. Then the sorted piles are merged back up the chain. Nobody ever looks at all 400 at once, the piles can be graded in parallel, and the only real work at each level is merging.
The paradigm
- 1
Divide
Split the input into
asubproblems, each a fraction1/bof the size (two halves, three thirds, one half you keep...). - 2
Conquer
Solve each subproblem recursively. When a subproblem is small enough (the base case), solve it directly.
- 3
Combine
Merge the sub-answers into the answer for the whole input. The cost of this step usually decides the complexity.
def solve(problem):
if is_small(problem):
return solve_directly(problem) # base case
parts = divide(problem) # a subproblems of size n / b
answers = [solve(p) for p in parts] # conquer (independent, parallelizable)
return combine(answers) # f(n) workThe visualization above shows merge sort, the textbook example: the array is split in half until single elements remain (trivially sorted), and the real work happens on the way back up, when sorted halves are merged.
Easy split, hard combine
- Merge sort: split at the midpoint for free
- All the work is in the O(n) merge
- Counting inversions, closest pair, maximum subarray
Hard split, easy combine
- Quick sort: partition around a pivot in O(n)
- Combining is just concatenation
- Quickselect, binary search (keep only one side)
How to recognize it
- The answer for the whole input can be built from answers for its halves plus some "crossing" information.
- The brute force is O(n²) over pairs, and pairs that straddle a split point can be handled cleverly (inversions, closest pair, reverse pairs).
- The input is sorted or monotone and you can discard a fraction of it each step (binary search, quickselect).
- Expression or tree structure: "all ways to parenthesize", building a tree from traversals.
- Numbers or matrices too large for direct multiplication (Karatsuba, Strassen).
Analyzing D&C with recurrences
If the algorithm makes a recursive calls on inputs of size n/b and does f(n) work to divide and combine, its running time satisfies the recurrence below. See Time & Space Complexity Analysis for recursion trees and the substitution method.
Draw the recursion tree. Level i has aⁱ subproblems of size n/bⁱ, so it does aⁱ · f(n/bⁱ) work. There are log_b n levels, and the bottom level has a^(log_b n) = n^(log_b a) leaves. Everything hinges on comparing the root's work f(n) with the leaves' work n^(log_b a).
The Master Theorem
| Case | Condition | Result | Intuition | Example |
|---|---|---|---|---|
| 1 | f(n) = O(n^(log_b a − ε)) for some ε > 0 | T(n) = Θ(n^(log_b a)) | Leaves dominate | Karatsuba: 3T(n/2) + n → Θ(n^1.585) |
| 2 | f(n) = Θ(n^(log_b a)) | T(n) = Θ(n^(log_b a) · log n) | Every level does equal work | Merge sort: 2T(n/2) + n → Θ(n log n) |
| 3 | f(n) = Ω(n^(log_b a + ε)) and a·f(n/b) ≤ c·f(n) for some c < 1 | T(n) = Θ(f(n)) | Root dominates | 2T(n/2) + n² → Θ(n²) |
| Algorithm | Recurrence | Solution |
|---|---|---|
| Binary search | T(n) = T(n/2) + O(1) | O(log n) |
| Merge sort | T(n) = 2T(n/2) + O(n) | O(n log n) |
| Quick sort (balanced pivots) | T(n) = 2T(n/2) + O(n) | O(n log n) |
| Quick sort (worst pivots) | T(n) = T(n − 1) + O(n) | O(n²) |
| Quickselect (expected) | T(n) = T(n/2) + O(n) | O(n) |
| Karatsuba | T(n) = 3T(n/2) + O(n) | O(n^1.585) |
| Strassen matrix multiply | T(n) = 7T(n/2) + O(n²) | O(n^2.807) |
| Tree traversal / max of array | T(n) = 2T(n/2) + O(1) | O(n) |
Classic examples
Merge sort and counting inversions
Merge Sort splits at the midpoint and merges in O(n): Θ(n log n) in every case, stable, with O(n) extra space. The merge step can count inversions for free: when an element from the right half is placed before the remaining k elements of the left half, it forms k inversions with them. The same trick solves Count of Smaller Numbers After Self and Reverse Pairs.
Quick sort and quickselect
Quick Sort does its work while dividing: partition around a pivot so smaller values go left and larger go right, then recurse on both sides. Balanced pivots give O(n log n); consistently bad pivots (the minimum each time) give O(n²), which is why pivots are randomized. Quickselect recurses into only the side that contains the k-th element, giving expected O(n).
Binary search: decrease and conquer
Binary Search is divide and conquer with a = 1: one comparison discards half the input, and there is nothing to combine. Fast exponentiation is the same shape: xⁿ = (x^(n/2))², so pow(x, n) takes O(log n) multiplications.
Maximum subarray
The best subarray lies entirely in the left half, entirely in the right half, or crosses the midpoint. The crossing case is the best suffix of the left half plus the best prefix of the right half, found in O(n). So T(n) = 2T(n/2) + O(n) = O(n log n).
Karatsuba multiplication
Schoolbook multiplication of two n-digit numbers costs O(n²). Split each number into a high and low half: x = x1·Bᵐ + x0 and y = y1·Bᵐ + y0. The product needs x1y1, x0y0 and the cross term x1y0 + x0y1, which looks like four multiplications. Karatsuba gets the cross term from one extra product:
def karatsuba(x: int, y: int) -> int:
if x < 10 or y < 10:
return x * y # base case: a single digit
m = max(len(str(x)), len(str(y))) // 2
base = 10 ** m
x1, x0 = divmod(x, base)
y1, y0 = divmod(y, base)
z2 = karatsuba(x1, y1)
z0 = karatsuba(x0, y0)
z1 = karatsuba(x1 + x0, y1 + y0) - z2 - z0 # the cross term from one product
return z2 * base * base + z1 * base + z0Closest pair of points
- 1
Sort and split
Sort points by x and split at the median x into left and right halves.
- 2
Recurse
Find the closest distance in each half; let
δbe the smaller of the two. - 3
Build the strip
Only pairs that straddle the split line and lie within
δof it can beatδ. Collect those points, ordered by y. - 4
Check a few neighbors
A packing argument shows each strip point needs to be compared with at most 7 following points in y order, so the strip costs O(n).
- 5
Total
Keeping points sorted by y via a merge on the way up gives
T(n) = 2T(n/2) + O(n) = O(n log n), versus O(n²) for checking all pairs.
Divide and conquer vs dynamic programming
Divide and conquer
- Subproblems are independent (disjoint halves)
- Each subproblem is solved once naturally
- Easy to parallelize
- Merge sort, quick sort, Karatsuba
Dynamic programming
- Subproblems overlap and recur many times
- Answers are cached (memoization) or tabulated
- Often turns exponential recursion into polynomial time
- Fibonacci, knapsack, edit distance
Practical concerns
- Recursion depth: balanced splits give O(log n) depth, but unbalanced ones (bad quick sort pivots) can reach O(n) and overflow the stack. Recurse on the smaller side and loop on the larger.
- Small-input cutoff: below ~16 elements, insertion sort beats recursion overhead. Production sorts (Timsort, introsort) switch algorithms for small ranges.
- Parallelism: independent subproblems map naturally onto fork/join pools, MapReduce and GPUs.
- Midpoint overflow: compute
lo + (hi - lo) / 2rather than(lo + hi) / 2in fixed-width integer languages. - Memory: merge-based algorithms need an O(n) buffer; allocate it once and reuse it instead of allocating per call.
Complexity
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Merge sort / inversion count | O(n log n) | O(n) | Every case |
| Quick sort | O(n log n) | O(log n) | Average; worst case O(n²) |
| Binary search | O(log n) | O(1) | Iterative version |
| Fast exponentiation | O(log n) | O(log n) | Recursive; O(1) iteratively |
| Maximum subarray (D&C) | O(n log n) | O(log n) | Kadane is O(n) |
| Karatsuba | O(n^1.585) | O(n) | n = number of digits |
| Closest pair of points | O(n log n) | O(n) | Brute force is O(n²) |
Space for recursive algorithms includes the call stack: O(log n) for balanced splits.
Implementation
Sorts the array and counts pairs `i < j` with `a[i] > a[j]`, all in O(n log n).
def sort_and_count(a: list[int]) -> int:
"""Sorts a in place and returns the number of inversions."""
buf = [0] * len(a)
def rec(lo: int, hi: int) -> int: # sorts a[lo:hi]
if hi - lo <= 1:
return 0
mid = (lo + hi) // 2
count = rec(lo, mid) + rec(mid, hi) # conquer both halves
i, j, k = lo, mid, lo
while i < mid and j < hi: # combine: merge
if a[i] <= a[j]:
buf[k] = a[i]; i += 1
else:
buf[k] = a[j]; j += 1
count += mid - i # a[j] jumps over the rest of the left half
k += 1
while i < mid:
buf[k] = a[i]; i += 1; k += 1
while j < hi:
buf[k] = a[j]; j += 1; k += 1
a[lo:hi] = buf[lo:hi]
return count
return rec(0, len(a))Key takeaways
- Divide and conquer = split into independent subproblems, solve recursively, combine.
- Running time follows
T(n) = a·T(n/b) + f(n); comparef(n)withn^(log_b a)to apply the Master Theorem. - Merge sort is easy split / hard combine; quick sort is hard split / easy combine.
- Karatsuba trades one multiplication for a few additions to reach O(n^1.585); closest pair reaches O(n log n) with a strip argument.
- If subproblems overlap, cache them: that is dynamic programming, not plain D&C.
Common pitfalls
- Applying the Master Theorem to uneven or subtract-by-one recurrences where it does not hold.
- Forgetting the base case or making the subproblem not strictly smaller, causing infinite recursion.
- Allocating a new buffer in every merge call, which adds heavy constant factors.
- Ignoring worst-case recursion depth (quick sort on sorted input with a fixed pivot).
- Overflowing when computing
(lo + hi) / 2or when counting inversions in a 32-bit int.
Interview tips
- State the three steps explicitly, then write and solve the recurrence.
- For "count pairs with a property" problems, consider counting the crossing pairs during the merge step.
- If asked for maximum subarray, give Kadane first, then mention the D&C version and why it is useful for segment trees.
Real-world applications
- Sorting libraries (merge sort in Timsort, quick sort in introsort) and external sorting of huge files.
- Big-integer arithmetic in cryptography (Karatsuba, Toom-Cook, FFT-based multiplication).
- Computational geometry: closest pair, convex hull, Delaunay triangulation.
- Parallel frameworks such as fork/join and MapReduce.
Practice problems
Test yourself
What does the Master Theorem give for T(n) = 2T(n/2) + O(n)?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.