Learn the pattern · ~15 min
Meet in the Middle
also called MITM, split and merge
When 2ⁿ is too many but 2^(n/2) is fine, split the items in half, list every choice for each half, and match the halves with sorting and binary search (or a hash map).
Reach for it when you read
- +"Choose any subset" with n around 30–40: 2ⁿ is about 10¹², but 2^(n/2) is about 10⁶.
- +The subset sum must hit, or come closest to, a target, and the values are too large for a knapsack DP table.
- +Split an array into two groups (often of equal size) to minimise the difference of their sums.
- +Four lists, pick one from each to reach a total: pair them up two and two.
- +A path or sequence of about 40 moves: walk half from the start, half from the end, match in the middle.
Not this one when
- ×n ≤ 20: list all 2ⁿ subsets directly, or use a bitmask DP.
- ×Values are small (sum up to about 10⁵): a 0/1 knapsack table is simpler and faster.
- ×Only pairs from one sorted array: plain two pointers or a hash map, no subsets needed.
Learn Meet in the Middle
First, why "in the middle"?
Picture two searches, one starting from each end, that stop when they meet halfway. Meet in the middle splits a problem the same way: cut the input into two halves, solve each half completely on its own, then match the two lists of answers.
It's the trick for "try every subset" when n is around 40, too many for brute force and too few to need anything cleverer.
How many subsets does a half have?
Each item is either in or out: two choices. With k items that's 2 × 2 × … × 2 = 2ᵏ subsets, and each subset has one sum. So:
| items | subsets |
|---|---|
| 2 | 2² = 4 |
| 20 | 2²⁰ = 1,048,576, about 10⁶ |
| 40 | 2⁴⁰ = 1,099,511,627,776, about 1.1 × 10¹² |
Split 40 items into two halves of 20 and each half has only 2²⁰ ≈ 10⁶ sums. A computer lists 10⁶ numbers in a blink; 10¹² it never finishes.
How do we list a half's sums?
The rule:
Start with the empty subset, sum 0. Each new item doubles the list: keep every old sum, and add a copy of each old sum with the item included.
For the half [7, −9]:
| item | what happens | list |
|---|---|---|
| start | only the empty subset | 0 |
| 7 | keep 0; add 0 + 7 | 0, 7 |
| −9 | keep 0 and 7; add 0 − 9 and 7 − 9 | 0, 7, −9, −2 |
Four sums for two items, one per subset: {}, {7}, {−9}, {7, −9}. Each row doubles the list, which is exactly why k items give 2ᵏ sums.
The code for it
vector<long long> sums(const vector<int>& a, int from, int to) {
vector<long long> s = {0}; // the empty subset
for (int i = from; i < to; i++) {
int k = s.size(); // only the old sums get a[i]
for (int j = 0; j < k; j++) s.push_back(s[j] + a[i]);
}
return s;
}You don't need to memorise this. It's the table above: start at 0, and for each item copy every old sum with the item added.
Why save k = s.size() before the inner loop? Because the loop pushes into s while it reads it. Without k, it would also read the sums it just added and add the same item to them a second time, and the list would never stop growing.
Fine, but how does this help us?
Here's a classic problem: Closest Subsequence Sum. Pick any subset of [7, −9, 15, −2] so its sum lands as close as possible to goal = −5. Return the distance.
By hand, split it into the left half [7, −9] (sums 0, 7, −9, −2) and the right half [15, −2] (sums 0, 15, −2, 13). Every subset of the whole array is one left subset plus one right subset, so all 16 sums fit in a grid. Each cell is left + right, with its distance to −5 in brackets:
| left \ right | 0 | 15 | −2 | 13 |
|---|---|---|---|---|
| 0 | 0 (5) | 15 (20) | −2 (3) | 13 (18) |
| 7 | 7 (12) | 22 (27) | 5 (10) | 20 (25) |
| −9 | −9 (4) | 6 (11) | −11 (6) | 4 (9) |
| −2 | −2 (3) | 13 (18) | −4 (1) | 11 (16) |
The best is −4 = 7 − 9 − 2, distance 1.
The brute force
The grid has 2ⁿ cells. The brute force fills all of them, one bitmask per subset:
long long bruteClosest(const vector<int>& a, long long goal) {
int n = a.size();
long long best = LLONG_MAX;
for (long long mask = 0; mask < (1LL << n); mask++) { // 2^n subsets
long long s = 0;
for (int i = 0; i < n; i++)
if (mask >> i & 1) s += a[i];
best = min(best, llabs(s - goal));
}
return best;
}It's correct, but for n = 40 there are 2⁴⁰ ≈ 1.1 × 10¹² subsets, each summed over 40 items. That's hours, not seconds. Time limit exceeded.
The one thought that fixes it
Stop at the last row, left sum x = −2. The total is −2 + (right sum), and we want it near −5. So the best right sum is the one nearest −5 − (−2) = −3. We don't need to look at the whole row: it's a question about the right list alone, "which value is nearest −3?".
Sort the right list once: [−2, 0, 13, 15]. Now "nearest to −3" is a binary search. The nearest value is either the first one ≥ −3, or the one just before it. Here the first one ≥ −3 is −2, and there is nothing before it, so −2 wins: distance |−2 − (−3)| = 1.
Do that for each of the 4 left sums, and you've checked all 16 cells while looking at only a few of them. At n = 40, you list 2²⁰ sums per side and do 2²⁰ binary searches, instead of 2⁴⁰ cells.
Equal halves matter. A 10 / 30 split would list 2³⁰ ≈ 10⁹ sums on one side, and you'd be back to too slow.
The code for the problem
long long closest(const vector<int>& a, long long goal) {
int h = a.size() / 2;
vector<long long> L = sums(a, 0, h), R = sums(a, h, a.size());
sort(R.begin(), R.end());
long long best = LLONG_MAX;
for (long long x : L) {
long long want = goal - x; // the perfect partner
auto it = lower_bound(R.begin(), R.end(), want);
if (it != R.end()) best = min(best, llabs(*it - want));
if (it != R.begin()) best = min(best, llabs(*prev(it) - want));
}
return best;
}Dry run
Left sums [0, 7, −9, −2], right sums sorted [−2, 0, 13, 15], goal −5.
| x (left) | want = −5 − x | first ≥ want, and the one before | distance | best |
|---|---|---|---|---|
| 0 | −5 | −2, nothing before | 3 | 3 |
| 7 | −12 | −2, nothing before | 10 | 3 |
| −9 | 4 | 13, and 0 before it | 9 and 4 | 3 |
| −2 | −3 | −2, nothing before | 1 | 1 |
Distance 1, the same answer as the brute force.
Why it's O(2^(n/2) · n)
Count what each half costs. Listing it is 2^(n/2) pushes. Sorting the right list is 2^(n/2) × log(2^(n/2)) = 2^(n/2) × n/2 steps. Each of the 2^(n/2) left sums does one binary search of n/2 steps. So the total is about 2^(n/2) · n. At n = 40: about 2²⁰ × 40 ≈ 4 × 10⁷ steps. Space is the two lists, 2²⁰ numbers each.
From 1.1 × 10¹² down to 4 × 10⁷, by solving two halves and searching one from the other.
Count subsets with an exact sum? Count the equal ones
Instead of the nearest partner, count how many right sums equal x₀ − x. In the loop over left sums:
auto [lo, hi] = equal_range(R.begin(), R.end(), x0 - x);
count += hi - lo; // every right sum equal to x0 - xFor [7, −9, 15, −2] and x₀ = 13 that finds 2 subsets: {15, −2} and {7, −9, 15}. A hash map of right sums works too.
No binary search? Two pointers
Sort both lists. Start with the smallest left sum and the biggest right sum. If their total is below the goal, move the left pointer up; otherwise move the right pointer down. Each step drops one value that can't do better, so it's a linear walk over both lists. On our example it meets −4 and also finds distance 1.
Four arrays, a + b + c + d = 0?
Same idea with two "halves" of two arrays each: put every a + b in a hash map, then look up −(c + d) for every pair. n⁴ becomes n². That's 4Sum II.
Remember this
- n ≈ 30–40 with "any subset": split in half. n ≤ 20 is plain brute force or bitmask DP; small values mean knapsack DP.
- Split evenly, list both halves, sort one, binary-search from the other.
- The nearest value is the first one ≥ the target or the one before it: check both, and check the iterators before you read them.
- Sums of 20 numbers can overflow
int: uselong long.
Practise it on 4Sum II, then Meet in the Middle (count the exact sums), Closest Subsequence Sum (the problem above), Partition Array Into Two Arrays to Minimize Sum Difference (group sums by how many items) and Tallest Billboard (three choices per item).
Watch it work, line by line
Closest Subsequence Sum ↗, nums = [7, -9, 15, -2], goal = -5 → 1 (7 + -9 + -2 = -4). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 4 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Is n around 30 to 45, so 2ⁿ is too slow but 2^(n/2) fits, and can a full answer be built from one left half plus one right half?
Reach for it when
- +n around 35-45 where 2n is too big but 2^(n/2) is fine
- +subset sum / closest sum with huge values
- +path in grid of size ~20x20 with XOR
- +n <= 40-45
It fails when
- ×Values are small enough for a sum-indexed tableuse Knapsack DP
- ×The combine step needs full state, not a pair of half-resultsuse No clean split; meet in the middle does not apply
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why does splitting in half help so much?Reveal
2 × 2^(n/2) sums instead of 2ⁿ subsets: about 2 × 10⁶ instead of 10¹² at n = 40.
2For a left sum x, what do you look for on the right?Reveal
goal − x: the nearest value (check at and just below it) for closest, equal values for counting.3When must each half also remember how many items it used?Reveal
When the total number of items is fixed: pair half-results of size i with size k − i.
Practice ladder
- 1Two Sumstore one side, look up the otherEasy
- 2Subsetslist every subsetMedium
- 34Sum IIfour lists into twoMedium
- 4Meet in the Middleexact countMedium
- 5Closest Subsequence Sumthe hookHard
- 6Tallest Billboardthree choices per itemHard
- 7Partition Array Into Two Arrays to Minimize Sum Differencefixed number of itemsHard
- 8Xor-Pathspaths split at the middle2100
Finished Meet in the Middle? Mark it done and Lessgo moves you to the next step.