Divide and conquer
Split a problem into independent subproblems and combine their answers efficiently.
By Invicly Tech, , in Data Structures & Algorithms. About 12 minutes to read.
In short
Divide and conquer splits a problem into independent subproblems, solves each recursively and combines the results. Merge sort, quicksort, binary search and fast multiplication all follow this pattern. The cost is captured by a recurrence like T(n) = 2T(n/2) + O(n).
Explained simply
Divide and conquer is a strategy for big problems: cut the problem into smaller pieces of the same kind, solve each piece, then join the answers. The pieces are solved the same way, so the idea repeats until the pieces are tiny and easy.
Imagine checking 1,000 exam papers alone. You could split them into two piles and give each to a helper. Each helper splits their pile again, and so on, until each person has one paper. Marking one paper is easy. Then the scores travel back up and are added together.
The power comes from halving. A problem of size one million needs only about 20 rounds of halving to reach size one. If joining the answers is cheap, the whole job becomes much faster than handling everything at once.
Merge sort, quicksort and binary search are all divide and conquer. So are fast ways to multiply huge numbers and to find the closest pair of points on a map.
Press Play on a diagram to walk through it one step at a time.
- Step 1Divide
Split input, often in half.
- Step 2Conquer
Solve each part recursively.
- Step 3Combine
Merge partial answers.
- Step 4Base case
Tiny inputs solved directly.
- Level 1: two of size n/2
- Work n/2 + n/2 = n
- Level 2: four of size n/4
- Work 4 x n/4 = n
- Level log2 n: n leaves
- Work n x 1 = n
- Total
- n per level x (log2 n + 1) levels = O(n log n)
In depth
Reading recurrences with the master theorem
A divide-and-conquer algorithm that makes a calls on pieces of size n / b and does f(n) extra work has running time T(n) = a T(n / b) + f(n). Compare f(n) with n^(log_b a), the number of leaves in the recursion tree.
If f(n) is smaller (polynomially), the leaves dominate: T(n) = O(n^(log_b a)). If they match, every level does the same work and you pay a log factor: T(n) = O(n^(log_b a) log n). If f(n) is larger (and regular), the top level dominates: T(n) = O(f(n)).
Examples: binary search is T(n) = T(n/2) + O(1), so a = 1, b = 2, n^0 = 1 matches f, giving O(log n). Merge sort is 2T(n/2) + O(n), matching again: O(n log n). Tree traversal 2T(n/2) + O(1) gives O(n). A naive split with 4T(n/2) + O(n) gives O(n^2).
- T(n) = a T(n/b) + f(n)
- Compare f(n) with n^(log_b a)
- Equal: multiply by log n
- T(n) = T(n/2) + O(1)
- O(log n)
- Binary search
- T(n) = 2T(n/2) + O(n)
- O(n log n)
- Merge sort, closest pair
- T(n) = 3T(n/2) + O(n)
- O(n^1.585)
- Karatsuba multiplication
Maximum subarray: the crossing case
Split the array at mid. The best subarray lies entirely in the left half, entirely in the right half, or it crosses the middle. The first two come from recursion. The crossing case is the clever combine step.
A crossing subarray must include a[mid] and a[mid + 1]. So the best one is the best sum ending exactly at mid (scan left from mid) plus the best sum starting exactly at mid + 1 (scan right). Those two scans cost O(n) together, so T(n) = 2T(n/2) + O(n) = O(n log n).
You can make the combine O(1) by having each call return four numbers: total sum, best prefix, best suffix and best overall. Then best = max(left.best, right.best, left.suffix + right.prefix). This gives O(n) total and is the idea behind segment trees that answer max-subarray queries on ranges.
- Three candidates: left, right, crossing
- Crossing = best suffix of left + best prefix of right
- Returning (sum, prefix, suffix, best) makes it O(n)
Counting inversions while merging
An inversion is a pair i < j with a[i] > a[j]. It measures how unsorted an array is: 0 for sorted, n(n-1)/2 for reversed. Checking every pair is O(n^2).
Divide and conquer does it in O(n log n). Count inversions inside the left half, inside the right half, and those that cross. While merging two sorted halves, each time you take an element from the right half before the remaining left elements, it is smaller than all of them. If len(left) - i items remain in the left half, add that many crossing inversions at once.
Uses: measuring how similar two rankings are (Kendall tau distance), and predicting the cost of insertion sort, which does exactly one shift per inversion.
- 1Compare 2 and 1
Take 1 from right; 2 left items remain: +2.
- 2Compare 2 and 3
Take 2 from left: +0.
- 3Compare 5 and 3
Take 3 from right; 1 left item remains: +1.
- 4Drain
Take 5. Output [1, 2, 3, 5].
- 5Total
3 crossing inversions: (2,1), (5,1), (5,3).
When the combine step is the whole trick
Many famous algorithms differ only in how cleverly they combine. Karatsuba multiplication splits two n-digit numbers into halves and needs only 3 half-size products instead of 4, using (a + b)(c + d) - ac - bd for the middle term. That changes 4T(n/2) + O(n) = O(n^2) into 3T(n/2) + O(n) = O(n^1.585). CPython uses Karatsuba for very large integers.
The closest pair of points sorts by x, splits at the median, and only needs to check points in a narrow strip around the split line. Inside that strip each point needs comparing with at most a constant number of neighbours (7 is a common bound) when sorted by y, giving O(n log n).
Strassen's matrix multiplication uses 7 half-size products instead of 8, giving O(n^2.807).
When not to divide and conquer
Divide and conquer assumes the subproblems are independent: solving the left half tells you nothing you need for the right half, and the same subproblem does not appear twice. When subproblems overlap, as in Fibonacci or edit distance, plain recursion repeats work exponentially. That is the signal to use dynamic programming, which stores each subproblem's answer.
Also watch the overheads. Splitting into tiny pieces costs function calls and memory. Real implementations stop recursing below a cutoff (for example 16 to 64 elements) and use a simple method like insertion sort there. This is why library sorts are hybrids.
Finally, the split must be balanced enough. Halving gives log n levels. Peeling off one element per level (as quicksort does with a bad pivot) gives n levels and quadratic time.
- Overlapping subproblems: use DP
- Use a cutoff for small inputs
- Unbalanced splits lose the log factor
Learn it in 4 short steps
About 40m each. Track them with a timer in your plan.
- 1Identify divide, conquer and combine steps~40m
- 2Solve maximum subarray with divide and conquer~40m
- 3Analyse with recurrences~40m
- 4Count inversions during merging~40m
Key points
- Two halves plus linear combine gives O(n log n).
- One half plus constant work gives O(log n), as in binary search.
- Counting inversions piggybacks on merge sort in O(n log n).
- Subproblems must be independent; overlapping ones call for DP instead.
Key terms
Tap a card to flip it. 0/3 known
Examples
def max_subarray(a, lo, hi): # O(n log n)
if lo == hi:
return a[lo]
mid = (lo + hi) // 2
best_left = best_right = float('-inf')
s = 0
for i in range(mid, lo - 1, -1):
s += a[i]; best_left = max(best_left, s)
s = 0
for i in range(mid + 1, hi + 1):
s += a[i]; best_right = max(best_right, s)
return max(max_subarray(a, lo, mid), max_subarray(a, mid + 1, hi),
best_left + best_right)
print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4], 0, 8)) # 6Kadane's algorithm solves this in O(n), but the structure shows the pattern.
Counting inversions in O(n log n)
For [3, 1, 2, 5, 4], the inversions are (3,1), (3,2) and (5,4), so the answer is 3. The function sorts and counts at once. Each call returns the sorted list and the count of inversions inside it. When a right-half element is taken first, all remaining left-half elements are bigger, so we add len(left) - i in one step.
def sort_count(a):
if len(a) <= 1:
return a, 0
mid = len(a) // 2
left, x = sort_count(a[:mid])
right, y = sort_count(a[mid:])
out, i, j, cross = [], 0, 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
cross += len(left) - i
return out + left[i:] + right[j:], x + y + cross
print(sort_count([3, 1, 2, 5, 4])[1]) # 3Maximum subarray in O(n) with a four-value combine
Each call returns (total, best prefix, best suffix, best). For a single element x, all four are x. To combine left L and right R: total = L.total + R.total; prefix = max(L.prefix, L.total + R.prefix); suffix = max(R.suffix, R.total + L.suffix); best = max(L.best, R.best, L.suffix + R.prefix). The combine is O(1), so T(n) = 2T(n/2) + O(1) = O(n).
def solve(a, lo, hi):
if lo == hi:
x = a[lo]
return x, x, x, x
mid = (lo + hi) // 2
lt, lp, ls, lb = solve(a, lo, mid)
rt, rp, rs, rb = solve(a, mid + 1, hi)
return (lt + rt, max(lp, lt + rp), max(rs, rt + ls),
max(lb, rb, ls + rp))
a = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(solve(a, 0, len(a) - 1)[3]) # 6Quick reference
- Template: if small, solve directly; else split, recurse, combine
- T(n) = 2T(n/2) + O(n) is O(n log n); T(n) = T(n/2) + O(1) is O(log n)
- T(n) = 2T(n/2) + O(1) is O(n); T(n) = 4T(n/2) + O(n) is O(n^2)
- Karatsuba: 3 half-size products, O(n^1.585); Strassen: 7, O(n^2.807)
- Inversions: add len(left) - i whenever the merge takes from the right
- Overlapping subproblems mean dynamic programming, not divide and conquer
- Real code switches to a simple method below a small cutoff
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Write find_max(a, lo, hi) using divide and conquer: split in half, find each half's maximum, return the larger. State its recurrence and time. Example: find_max([3, 9, 2, 7], 0, 3) is 9.
- Exercise 2medium
Write majority(a, lo, hi) that returns the element appearing more than half the time in a[lo..hi] using divide and conquer, assuming one exists. Example: [2, 2, 1, 1, 2, 2, 3] gives 2.
- Exercise 3hard
Write karatsuba(x, y) for non-negative integers. Split each number at m decimal digits, compute three products recursively, and check against x * y. Example: karatsuba(1234, 5678) is 7006652.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- Is divide and conquer the same as recursion?
- No. Recursion is a coding technique; divide and conquer is a problem-solving strategy that is usually written recursively, but can also be iterative, like bottom-up merge sort.
- Do I need the master theorem in interviews?
- Rarely by name, but you should know the common results: one half with O(1) work is O(log n), two halves with O(n) work is O(n log n).
- Can divide and conquer run in parallel?
- Yes, and that is one of its strengths. Independent subproblems can run on different cores, which is how parallel merge sort and many MapReduce jobs work.