Divide and Conquer
How divide and conquer splits a problem, solves the parts and combines them, how to count inversions and compute powers fast, and what interviewers ask.
On this page
Divide and conquer solves a problem by splitting the input into smaller parts, solving each part with the same function, and combining the answers. It is used when a problem is too slow to solve directly but becomes cheap once the parts are solved, which is how binary search and merge sort work. You reach for it when the input can be cut in half and the answer for the whole can be built from the answers for the halves.
The standard example is counting inversions: pairs of positions where a bigger number comes before a smaller one. Checking every pair takes O(n²) comparisons, and divide and conquer counts them in O(n log n).
How divide and conquer works
The algorithm has three steps:
- Divide the input into smaller parts, usually two halves.
- Conquer each part by calling the same function on it. A part small enough to answer directly, such as an empty list or a single item, is the base case.
- Combine the answers for the parts into the answer for the whole.
Dividing and conquering are usually a few lines each. The design work is in the combine step: after both halves are solved, you have to find what is still unanswered, which is whatever involves both halves, and compute it cheaply. The running time of the whole algorithm is mostly the cost of that step.
Counting inversions with merge sort
Take the list [3, 6, 5, 1, 4, 2]. Split it into [3, 6, 5] and [1, 4, 2]. Every inversion is in the left half, in the right half, or crosses the middle, with the bigger number on the left and the smaller on the right. The two recursive calls count the first two kinds, so the combine only has to count the crossing pairs.
The number of crossing pairs does not depend on the order of the items inside each half, because every left item is before every right item either way. So each recursive call can return its half sorted as well as counted, and the combine is then a merge, exactly as in merge sort. During the merge, when the next right item is smaller than the front of the left half, it is smaller than every item still waiting in the left half, because the left half is sorted. All of those waiting items form an inversion with it, and you add their number to the count in one step.
merge left and right, counting as you go:while both halves have items: if left[i] <= right[j]: take left[i] else: cross += items still waiting in left take right[j]copy whatever remains- left (sorted)03i1526right (sorted)01j1224merged
- inside
- 2
- cross
- 0
1The halves have come back sorted. Each contains 1 inversion: 6 before 5 on the left, and 4 before 2 on the right.
- left (sorted)03i1526right (sorted)0112j24merged01
- inside
- 2
- cross
- 3
21 is smaller than 3, so the merge takes 1. It is smaller than 3, 5 and 6, which are all still waiting on the left, so add 3.
- left (sorted)03i1526right (sorted)011224jmerged0112
- inside
- 2
- cross
- 6
32 is smaller than 3, so the merge takes 2. All three left items are still waiting, so add 3 again.
- left (sorted)0315i26right (sorted)011224jmerged011223
- inside
- 2
- cross
- 6
43 is smaller than 4, so the merge takes 3 from the left. Nothing is added, because a left item that comes first is in the right order.
- left (sorted)0315i26right (sorted)011224jmerged01122334
- inside
- 2
- cross
- 8
54 is smaller than 5, so the merge takes 4. Only 5 and 6 are still waiting on the left, so add 2.
- left (sorted)031526iright (sorted)011224jmerged011223344556
- inside
- 2
- cross
- 8
6The right half is empty, so 5 and 6 are copied across. No further pairs are counted.
- merged011223344556
- inside
- 2
- cross
- 8
- total
- 10
7The total is 2 inside the halves plus 8 across the middle, which is 10 inversions out of 15 pairs, found without comparing every pair.
// Returns [sorted copy of a, number of inversions in a].
function sortAndCount(a) {
if (a.length <= 1) return [a, 0];
const mid = Math.floor(a.length / 2);
const [left, leftCount] = sortAndCount(a.slice(0, mid));
const [right, rightCount] = sortAndCount(a.slice(mid));
const merged = [];
let i = 0, j = 0, cross = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
merged.push(left[i++]);
} else {
cross += left.length - i; // right[j] is smaller than every waiting left item
merged.push(right[j++]);
}
}
while (i < left.length) merged.push(left[i++]);
while (j < right.length) merged.push(right[j++]);
return [merged, leftCount + rightCount + cross];
}
sortAndCount([3, 6, 5, 1, 4, 2])[1]; // 10# Returns (sorted copy of a, number of inversions in a).
def sort_and_count(a):
if len(a) <= 1:
return a, 0
mid = len(a) // 2
left, left_count = sort_and_count(a[:mid])
right, right_count = sort_and_count(a[mid:])
merged = []
i = j = cross = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
cross += len(left) - i # right[j] is smaller than every waiting left item
merged.append(right[j])
j += 1
merged.extend(left[i:])
merged.extend(right[j:])
return merged, left_count + right_count + cross
sort_and_count([3, 6, 5, 1, 4, 2])[1] # 10The comparison uses <= so that on a tie the left item is taken first. Equal values are not an inversion, and this keeps them from being counted.
| Approach | Time | Space | Why |
|---|---|---|---|
| Check every pair | O(n²) | O(1) | n(n − 1) / 2 comparisons. |
| Divide and conquer | O(n log n) | O(n) | There are log n levels of splitting, and the merges on each level touch every item once. This is the same cost as merge sort. |
Working out the cost of a split
To find the running time of a divide and conquer algorithm, draw the tree of calls and add up the work on each level. Two numbers decide the result: how many smaller calls each call makes, and how much work the combine does. If the combine touches every item, as the merge does, each level costs n and there are log n levels, so the total is O(n log n). If the combine is constant, the number of calls doubles on each level, and the total is dominated by the n calls on the bottom level, so it is O(n).
These cases follow the recurrence T(n) = a·T(n/b) + f(n), where a is the number of calls, b is the factor by which the input shrinks and f(n) is the cost of the combine. The master theorem solves it by comparing f(n) with the work on the bottom level of the tree, but in an interview, drawing the tree as above is usually enough.
The table below lists the common cases. The variants section explains each one.
| Each call makes | Combine costs | Total | Example |
|---|---|---|---|
| 1 call on half | O(1) | O(log n) | binary search, fast power |
| 1 call on half | O(n) | O(n) | quickselect on average |
| 2 calls on halves | O(1) | O(n) | largest value by splitting in two |
| 2 calls on halves | O(n) | O(n log n) | merge sort, counting inversions |
Variants
Two halves with a linear combine
Merge sort and inversion counting are in this group. Both halves are solved, and the combine does O(n) work across them. The total is O(n log n). The same shape appears in problems such as counting, for each element, how many smaller elements come after it, or counting pairs where one value is more than twice another. In each case the halves are sorted on the way back up so that a single merge-style pass can count the crossing pairs.
One half only
Sometimes the answer lies entirely in one half, so you recurse on that half and ignore the other. Binary search does this: it compares with the middle item and keeps one side. With a constant combine, the cost is O(log n).
Fast power works the same way. To compute xn, note that 313 = 36 × 36 × 3, and 36 = 33 × 33. The two halves are the same problem, so it is solved once and the result is used twice. Each call halves the exponent and does one or two multiplications.
// x to the power n, for a whole number n >= 0
function power(x, n) {
if (n === 0) return 1;
const half = power(x, Math.floor(n / 2)); // solve the half once
return n % 2 === 0 ? half * half : half * half * x;
}
power(3, 13); // 1594323# x to the power n, for a whole number n >= 0
def power(x, n):
if n == 0:
return 1
half = power(x, n // 2) # solve the half once
return half * half if n % 2 == 0 else half * half * x
power(3, 13) # 1594323For power(3, 13) the exponent goes 13, 6, 3, 1, 0, which is five calls and 7 multiplications, where a plain loop needs 12. An exponent of a billion needs only 31 calls, because the exponent can be halved only about 30 times. The cost is O(log n).
Quickselect, which finds the k-th smallest item, also keeps one half. It partitions the array as in quicksort and continues only in the side that contains position k. The partition is O(n), so the average cost is n + n/2 + n/4 + … which is about 2n, or O(n). The worst case is O(n²) when the pivots are consistently bad.
Splitting without a linear combine
If the combine is constant and both halves must be solved, the total is O(n), as in the right half of the figure. Finding the largest value by splitting the list in two and taking the larger of the two answers is an example. It is no faster than a simple loop, so a loop is the better choice here. Divide and conquer is worth the recursion only when it beats the direct approach, which means the combine must use something the halves provide, such as sortedness.
Other classic problems
Several well-known problems have the same shape. The closest pair of points solves each side of a dividing line and then checks only the points near the line. The maximum subarray sum solves each half and adds the best subarray that crosses the middle, though a single pass (Kadane's algorithm) is simpler and faster. Karatsuba multiplication and Strassen's matrix multiplication make three and seven recursive calls instead of four and eight, which lowers the exponent in the total cost.
When divide and conquer does not apply
The technique does not apply when the parts overlap, meaning the same smaller problem is solved many times. The naive recursive Fibonacci in Recursion is the standard case: its cost grows exponentially. When parts overlap, store the answers with dynamic programming. It also does not apply when the answer for the whole cannot be built from answers for the parts without redoing the work.
Pitfalls
In the interview
Signs that a problem needs divide and conquer:
- The statement asks you to count or find pairs
(i, j)withi < jthat satisfy a condition on the values, the input is large (around 105 items), and a nested loop is too slow. Inversions, "count smaller numbers after self" and "reverse pairs" are the usual cases. - The input is sorted, or can be sorted without changing the answer, and you need O(log n) or O(n log n).
- The problem asks for a power, or for any value that is built from two equal halves.
- The interviewer asks for O(n log n) and sorting alone does not solve the problem.
Questions to expect:
- "What is the time complexity, and how do you know?" It is O(n log n). The list is halved about log n times, and the merges on each level look at every item once, so each level costs O(n). Say that you add up the cost per level of the call tree, because that is the method that works for other splits too.
- "What is the space complexity?" The merge buffers need O(n) extra memory, and the recursion is only log n calls deep, so the call stack is not a concern. The slicing in the code above makes copies, but they are freed as the calls return, so the total extra memory at any moment stays O(n).
- "Why not just sort the list and compare it with the original?" Sorting loses where each item was, and the inversion count depends on the original positions. The merge is the step that counts the crossing pairs while it sorts.
- "Does it handle duplicates?" Yes, as long as the merge takes the left item on a tie. Then equal values are never counted as an inversion. If the problem counts equal values as pairs, switch the comparison to match.
- "Can you do it another way?" A Fenwick tree (binary indexed tree) counts, for each item, how many larger items came before it, also in O(n log n). It needs the values compressed to ranks first, and it processes the array in one pass without recursion.
- "What is the recurrence for merge sort, and how do you solve it?" It is T(n) = 2T(n/2) + O(n). Each level of the call tree does O(n) work in total and there are log n levels, so T(n) = O(n log n). The master theorem gives the same result.
- "When would divide and conquer be a bad choice?" When the subproblems overlap, as in Fibonacci, where dynamic programming is the fix. It is also a poor choice when a simple loop already solves the problem in O(n), because the recursion adds overhead and no speed.
During a merge, the left half is [2, 7, 9] with i on 7, and the next item in the right half is 4. How many inversions does taking 4 add?
An algorithm splits its input into two halves, recurses on both, and combines in O(1). What is its total cost?
Why does the inversion count sort each half before merging?
What to practise next
Quicksort puts the work in the divide step instead of the combine step. Intervals uses sorting to solve problems about ranges.