Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Divide and Conquer

Split the problem, solve the parts, combine the answers.

Merge sort orders a million items with about 20 levels of splitting, where comparing every pair would take half a trillion comparisons. Divide and conquer is that trick in general: split into independent subproblems, solve them recursively, and pay only for combining. Write down the recurrence, and the running time follows.

What you’ll learn

  • Write the divide, conquer and combine steps of an algorithm and its recurrence T(n)=a T(n/b)+f(n)T(n) = a\,T(n/b) + f(n), and solve it with the master theorem.
  • Count inversions in O(nlog⁡n)O(n \log n) time by piggybacking on merge sort, and prove the count correct.
  • Solve the maximum subarray problem through its crossing case, and make the combine step O(1)O(1) by returning summaries.
  • Explain when divide and conquer fails (overlapping or unbalanced subproblems, costly combining) and how it exposes parallelism.
  • Recognize divide-and-conquer problems: an answer made of a left part, a right part and a part that crosses the split.

The template and its recurrence

A divide-and-conquer algorithm does three things to an input of size nn: it divides it into aa subproblems of size about n/bn/b, conquers them recursively (inputs below some size are base cases, solved directly), and combines their answers with f(n)f(n) extra work. Its running time satisfies the recurrence

T(n)=a T(n/b)+f(n).T(n) = a\,T(n/b) + f(n).

The recursion tree reads it off: level ii holds aia^i calls of size n/bin/b^i, costing aif(n/bi)a^i f(n/b^i) in total, and there are about log⁡bn\log_b n levels.

AlgorithmRecurrenceSolution
Binary search, fast exponentiationT(n)=T(n/2)+O(1)T(n) = T(n/2) + O(1)O(log⁡n)O(\log n) worst case
Merge sort, counting inversionsT(n)=2T(n/2)+O(n)T(n) = 2T(n/2) + O(n)O(nlog⁡n)O(n \log n) worst case
Maximum subarray, closest pair of pointsT(n)=2T(n/2)+O(n)T(n) = 2T(n/2) + O(n)O(nlog⁡n)O(n \log n) worst case
Quickselectone subproblem of random size, plus O(n)O(n)O(n)O(n) expected
Karatsuba multiplicationT(n)=3T(n/2)+O(n)T(n) = 3T(n/2) + O(n)O(nlog⁡23)≈O(n1.585)O(n^{\log_2 3}) \approx O(n^{1.585})
Strassen matrix multiplicationT(n)=7T(n/2)+O(n2)T(n) = 7T(n/2) + O(n^2)O(nlog⁡27)≈O(n2.807)O(n^{\log_2 7}) \approx O(n^{2.807})

The quick way to read a recurrence: going one level down multiplies the level cost by a/bca / b^c. If that ratio exceeds 1, the costs grow geometrically toward the leaves and the nlog⁡ban^{\log_b a} leaves dominate; if it is exactly 1, all log⁡bn\log_b n levels cost the same; if it is below 1, the top-level combine dominates.

Merge sort and counting inversions

An inversion of an array aa is a pair of indices i<ji < j with a[i]>a[j]a[i] > a[j]. The number of inversions measures disorder: 0 for a sorted array, n(n−1)/2n(n-1)/2 for a reversed one. Checking every pair counts them in O(n2)O(n^2) time, and so, implicitly, does insertion sort, which removes exactly one inversion per shift.

Divide and conquer counts them in O(nlog⁡n)O(n \log n). Split aa into halves LL and RR. Every inversion lies inside LL, inside RR, or crosses, with ii in LL and jj in RR. Count the first two recursively. For the crossing pairs, notice that sorting each half does not change them, since it only reorders elements within a half. So let the recursion also return each half sorted, and count the crossing pairs while merging:

python
def sort_count(a):                      # returns (sorted copy of a, number of inversions)
    if len(a) <= 1:
        return a[:], 0
    mid = len(a) // 2
    left, x = sort_count(a[:mid])
    right, y = sort_count(a[mid:])
    merged, i, j, cross = [], 0, 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:          # <= keeps equal keys out of the count
            merged.append(left[i]); i += 1
        else:                            # right[j] is smaller than all of left[i:]
            merged.append(right[j]); j += 1
            cross += len(left) - i
    merged += left[i:] + right[j:]
    return merged, x + y + cross

T(n)=2T(n/2)+O(n)T(n) = 2T(n/2) + O(n), so O(nlog⁡n)O(n \log n) in the worst case. When right[j] is output before left[i], it is smaller than left[i] and all the later elements of the sorted left half, which gives exactly len(left) - i crossing inversions with right[j], each counted once.

Predict before you look

How many inversions does [8,3,12,5,1,14,7,10][8, 3, 12, 5, 1, 14, 7, 10] have?

Show the answer

12

Count, for each element, the later elements smaller than it: 8 has 4 (3, 5, 1, 7), 3 has 1, 12 has 4 (5, 1, 7, 10), 5 has 1, 1 has 0, 14 has 2, 7 has 0. Total 12, out of a possible 8⋅7/2=288 \cdot 7 / 2 = 28. In sort_count, the halves [8,3,12,5][8, 3, 12, 5] and [1,14,7,10][1, 14, 7, 10] contain 3 and 2 of them, and the top-level merge counts the other 7, the crossing ones.

The crossing case: maximum subarray

The maximum subarray problem asks for the largest sum of a nonempty contiguous block of aa. Brute force tries all O(n2)O(n^2) blocks, each in O(1)O(1) with prefix sums. Divide and conquer: the best block lies in the left half, in the right half, or crosses the middle, and a crossing block is a suffix of the left half followed by a prefix of the right half. So the best crossing block is the best suffix plus the best prefix, found by two scans outward from the middle.

python
def max_crossing_sum(a, lo, mid, hi):     # best a[i:j] with lo <= i < mid < j <= hi
    best_left, s = float('-inf'), 0
    for i in range(mid - 1, lo - 1, -1):  # best suffix of the left half
        s += a[i]
        best_left = max(best_left, s)
    best_right, s = float('-inf'), 0
    for j in range(mid, hi):              # best prefix of the right half
        s += a[j]
        best_right = max(best_right, s)
    return best_left + best_right

def max_subarray(a, lo=0, hi=None):       # best sum of a nonempty a[i:j], lo <= i < j <= hi
    if hi is None:
        hi = len(a)
    if hi - lo == 1:
        return a[lo]
    mid = (lo + hi) // 2
    return max(max_subarray(a, lo, mid), max_subarray(a, mid, hi),
               max_crossing_sum(a, lo, mid, hi))

Ranges are half-open, [lo,hi)[lo, hi). The crossing scans take O(n)O(n), so T(n)=2T(n/2)+O(n)=O(nlog⁡n)T(n) = 2T(n/2) + O(n) = O(n \log n) in the worst case.

Check your understanding

For a=[3,−4,5,−1,2,−6,4,1]a = [3, -4, 5, -1, 2, -6, 4, 1], the best block of the left half [3,−4,5,−1][3, -4, 5, -1] has sum 5, and so does the best block of the right half [2,−6,4,1][2, -6, 4, 1]. What does max_subarray(a) return?

  1. 5
  2. 6
  3. 10
  4. 4
Show the answer

B. 6

The best suffix of the left half is 5+(−1)=45 + (-1) = 4 and the best prefix of the right half is 22, so the best crossing block, [5,−1,2][5, -1, 2], sums to 6 and beats both halves.

When it works, when it does not, and parallelism

Divide and conquer pays off under three conditions:

  • Independent subproblems. If they overlap, the recursion recomputes them. Plain recursive Fibonacci satisfies T(n)=T(n−1)+T(n−2)+O(1)T(n) = T(n-1) + T(n-2) + O(1), which grows like φn\varphi^n with φ≈1.618\varphi \approx 1.618; storing answers (memoization) turns it into dynamic programming.
  • Balanced splits. Splitting off a constant amount makes the recursion nn levels deep: quicksort with a bad pivot satisfies T(n)=T(n−1)+O(n)=Θ(n2)T(n) = T(n-1) + O(n) = \Theta(n^2).
  • A cheap combine. If combining two halves costs Θ(n2)\Theta(n^2), then T(n)=2T(n/2)+Θ(n2)=Θ(n2)T(n) = 2T(n/2) + \Theta(n^2) = \Theta(n^2): the root dominates, and splitting gained nothing over brute force.

Independent subproblems can also run at the same time. In the fork-join model, the work T1T_1 is the running time on one processor and the span T∞T_\infty the length of the longest chain of steps that must happen one after another. On PP processors, a greedy scheduler finishes within T1/P+T∞T_1/P + T_\infty (Brent's bound), and Cilk's randomized work stealing achieves T1/P+O(T∞)T_1/P + O(T_\infty) in expectation (Blumofe & Leiserson, 1999).

text
MERGE-SORT(a, lo, hi):                 # sorts a[lo:hi]
    if hi - lo <= 1: return
    mid ← ⌊(lo + hi) / 2⌋
    spawn MERGE-SORT(a, lo, mid)        # the halves are independent:
    MERGE-SORT(a, mid, hi)              # run them in parallel
    sync                                # wait for both
    MERGE(a, lo, mid, hi)               # a serial merge: Θ(n) at the top

Work Θ(nlog⁡n)\Theta(n \log n). The span satisfies S(n)=S(n/2)+Θ(n)=Θ(n)S(n) = S(n/2) + \Theta(n) = \Theta(n), so the parallelism T1/T∞T_1 / T_\infty is only Θ(log⁡n)\Theta(\log n): the serial merge is the bottleneck.

Think first How can the merge itself be parallelized?

Take the middle element of the longer run, find its position in the other run by binary search, put it in its final place, then merge the two left parts and the two right parts in parallel. The merge's span becomes O(log⁡2n)O(\log^2 n), merge sort's O(log⁡3n)O(\log^3 n), and the parallelism Θ(n/log⁡2n)\Theta(n / \log^2 n) (Cormen et al., chapter on parallel algorithms).

Recognizing it

Signals. The answer for the whole is assembled from answers for two halves plus something computed across the split: a merge, pairs with one element on each side, a block that straddles the middle, points near a dividing line. "Count the pairs i<ji < j with some property" is a strong hint when the property can be checked across two sorted halves. With nn up to 10510^5 or 10610^6, the target is O(nlog⁡n)O(n \log n).

Problem (in our words)Divide-and-conquer ideaTime
Count the inversions of an arraycount crossing pairs while mergingO(nlog⁡n)O(n \log n)
Count pairs i<ji < j with a[i]>2 a[j]a[i] > 2\,a[j]before each merge, sweep two pointers across the sorted halvesO(nlog⁡n)O(n \log n)
Count subarrays whose sum lies in [lo,hi][lo, hi]the same on prefix sums: pairs i<ji < j with lo≤P[j]−P[i]≤hilo \le P[j] - P[i] \le hi across the halvesO(nlog⁡n)O(n \log n)
Closest pair of points in the planesplit by xx; a closer crossing pair must lie in a strip of width 2δ2\delta around the lineO(nlog⁡n)O(n \log n)
Merge kk sorted lists with NN elements in totalmerge the lists in pairs, round after roundO(Nlog⁡k)O(N \log k)
Majority element (more than n/2n/2 copies)a majority of the whole is a majority of one half; count both halves' candidatesO(nlog⁡n)O(n \log n); Boyer–Moore voting is O(n)O(n)

Key takeaways

  • Divide and conquer splits into aa independent subproblems of size n/bn/b and combines in f(n)f(n): T(n)=a T(n/b)+f(n)T(n) = a\,T(n/b) + f(n). The master theorem compares cc with log⁡ba\log_b a, that is, the level ratio a/bca / b^c with 1.
  • Counting inversions rides on merge sort: when an element of the right half is output, add the number of elements still waiting in the left half. O(nlog⁡n)O(n \log n) worst case.
  • Many answers decompose into left, right and crossing parts; for the maximum subarray the crossing part is a best suffix plus a best prefix, and returning summaries makes the combine O(1)O(1).
  • Divide and conquer needs independent, reasonably balanced subproblems and a cheap combine. Overlapping subproblems call for dynamic programming. Independent halves can run in parallel.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

An algorithm splits an input of size nn into 4 subproblems of size n/2n/2 and combines their answers in Θ(n)\Theta(n) time. What is its running time?

  1. Θ(n2)\Theta(n^2)
  2. Θ(nlog⁡n)\Theta(n \log n)
  3. Θ(n1.585)\Theta(n^{1.585})
  4. Θ(n2log⁡n)\Theta(n^2 \log n)
Show the answer

A. Θ(n2)\Theta(n^2)

Here a=4a = 4, b=2b = 2, c=1c = 1, and log⁡24=2>1\log_2 4 = 2 > 1: the leaves dominate, and there are 4log⁡2n=n24^{\log_2 n} = n^2 of them, so T(n)=Θ(n2)T(n) = \Theta(n^2). This is the naive split of nn-digit multiplication into four half-size products, no faster than the schoolbook method; Karatsuba's trick of three products is what brings the exponent down.

Question 2

Counting inversions with merge sort: the merge outputs right[j] while left[i], left[i+1], … are still waiting. How many crossing inversions does this add?

  1. j
  2. len(left) - i
  3. 1
  4. len(right) - j
Show the answer

B. len(left) - i

The left half is sorted and right[j] < left[i], so right[j] is smaller than every element still waiting in the left half: len(left) - i elements, each forming one crossing inversion with it. Elements already output from the left half are at most right[j] and form none.

Question 3

Naive recursive Fibonacci makes 331,160,281 calls to compute F40F_{40}, though only 41 distinct values F0,…,F40F_0, \dots, F_{40} exist. What is the fix?

  1. Split nn into halves instead of n−1n - 1 and n−2n - 2
  2. Run the two recursive calls in parallel
  3. Add a base case for n=2n = 2
  4. Remember each value the first time it is computed, or fill a table bottom-up: dynamic programming
Show the answer

D. Remember each value the first time it is computed, or fill a table bottom-up: dynamic programming

The subproblems overlap: F38F_{38} is needed by both F40F_{40} and F39F_{39}, and so on down. Divide and conquer treats every call as new; storing each of the 41 values once cuts the work to O(n)O(n) additions.

Question 4

Merge sort runs its two recursive calls in parallel but merges sequentially. Its work is Θ(nlog⁡n)\Theta(n \log n). What is its span, the running time on unboundedly many processors?

  1. Θ(log⁡n)\Theta(\log n)
  2. Θ(log⁡2n)\Theta(\log^2 n)
  3. Θ(n)\Theta(n)
  4. Θ(nlog⁡n)\Theta(n \log n)
Show the answer

C. Θ(n)\Theta(n)

The span satisfies S(n)=S(n/2)+Θ(n)S(n) = S(n/2) + \Theta(n): the two halves run at the same time, but the top-level merge alone takes Θ(n)\Theta(n). So S(n)=Θ(n)S(n) = \Theta(n), and the parallelism, work divided by span, is only Θ(log⁡n)\Theta(\log n). A parallel merge is needed to do better.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 4; the maximum-subarray example is §4.1 of the 3rd edition (2009).
  • J. Kleinberg & É. Tardos, Algorithm Design (Addison-Wesley, 2005), chapter 5.
  • J. Erickson, Algorithms (2019), chapter 1.
  • J. Bentley, "Programming pearls: algorithm design techniques," Communications of the ACM 27(9) (1984), 865–873.