Meet in the Middle
Split the search into halves: 2^(n/2) for subset sum and more.
Subset sum on 40 numbers means subsets: about three hours at per second. Split the numbers into two halves of 20 and list each half's subset sums instead. Every subset of the 40 is a pair of half-subsets, so the question becomes which two sums, one from each list, add up to the target, and sorting answers that in about a second, even in Python.
What you’ll learn
- Describe meet in the middle as splitting a search into two halves joined by a matching condition, and solve subset sum in time with Horowitz and Sahni's method.
- Prove that merging builds sorted subset-sum lists in linear time in their length, and that the two-pointer join never discards a matching pair.
- Explain Schroeppel and Shamir's -memory algorithm and the trade-off , and state what is known about beating .
- Recognize the same split in k-SUM, discrete logarithms, bidirectional search and attacks on double encryption, and state the k-SUM lower bound together with its model.
Split, enumerate, match
A backtracking search over binary choices visits up to leaves. Meet in the middle applies when the choices split into two halves whose contributions combine in a simple way, typically a sum: then a full solution is a pair (left half, right half) satisfying one equation, and the two halves can be enumerated separately, partial solutions in all, and matched.
For subset sum, with numbers and target : list the sums of all subsets of the first half and of the second half, sort them, and look for and with .
| Half | Its subset sums, sorted |
|---|---|
| 0, 2, 3, 4, 5, 6, 7, 9 | |
| 0, 5, 7, 9, 12, 14, 16, 21 | |
| Pairs with sum 12 | 0 + 12 = {5, 7}; 3 + 9 = {3, 9}; 5 + 7 = {2, 3, 7}; 7 + 5 = {3, 4, 5} |
import bisect
def subset_sums(a):
"""All 2^len(a) subset sums in sorted order, built by merging: O(2^len(a)) time."""
sums = [0]
for x in a:
shifted = [s + x for s in sums] # the same subsets, now with x
merged, i, j = [], 0, 0
while i < len(sums) and j < len(shifted):
if sums[i] <= shifted[j]:
merged.append(sums[i]); i += 1
else:
merged.append(shifted[j]); j += 1
sums = merged + sums[i:] + shifted[j:]
return sums
def count_subsets(a, target):
"""Number of subsets of a with sum exactly target (Horowitz-Sahni)."""
left, right = subset_sums(a[:len(a) // 2]), subset_sums(a[len(a) // 2:])
return sum(bisect.bisect_right(right, target - s) - bisect.bisect_left(right, target - s)
for s in left)
print(count_subsets([2, 3, 4, 5, 7, 9], 12)) # 4: {3,9}, {5,7}, {2,3,7}, {3,4,5}Checked against brute force on 500 random inputs with negative numbers allowed. For 40 random numbers below , counting the subsets that hit a target took about one second in CPython.
With the rule of thumb of simple operations per second, about how many seconds does the brute force over all subsets take, at one operation per subset?
Show the answer
11000 s
, and seconds, about three hours, before even counting the work per subset. Meet in the middle handles sums plus sorting and matching: milliseconds in a compiled language.
Why it is correct, and how fast
Sorted lists in linear time. Let be the sorted subset sums of . A subset of the first numbers either omits or contains it, so is the merge of two sorted lists of length , which costs ; over all the costs form a geometric series:
The two-pointer join. Scan upward from its smallest element and downward from its largest. If , then cannot pair with , the largest sum left in , nor with anything smaller, so discard ; if , discard symmetrically. Each step discards one element and never a member of a matching pair, so a match is found if one exists, after at most
Counting and bounds. Counting needs multiplicities of equal sums, so a binary search into for each , as in the code, costs a factor . For "the largest sum at most ", the same downward pointer gives each its best partner. Each of the subsets is a pair, so nothing is missed:
The idea in one sentence: the search tree has leaves, but a leaf is determined by its two halves, and you can afford to list each half on its own. The square root of the work is the most a split into two halves can save. Splitting into more parts does not help directly, because the parts must still be combined into pairs of halves, but it does help memory, as the next step shows.
Values do not matter: the numbers may be negative or as large as . That is the difference from the pseudo-polynomial dynamic program over sums, (see Pseudo-Polynomial Time), which wins when the values are small and loses badly when they are huge.
Saving memory: Schroeppel and Shamir
The weak point of Horowitz and Sahni is memory: for each half has sums, terabytes of them. Schroeppel and Shamir (1981) split the numbers into four quarters instead, with sorted subset-sum lists of entries each. The join still needs all sums in increasing order and all sums in decreasing order, but it reads each stream only once, front to back, so the streams can be generated on the fly.
A min-heap holding one candidate per element of produces the sums in increasing order: pop the smallest , push . That is a -way merge of sorted lists, with heap entries.
import heapq
def ascending_pair_sums(P, Q):
"""Yield p + q for all p in P, q in Q (both sorted) in increasing order, with len(P) heap entries."""
heap = [(p + Q[0], i, 0) for i, p in enumerate(P)]
heapq.heapify(heap)
while heap:
s, i, j = heapq.heappop(heap)
yield s
if j + 1 < len(Q):
heapq.heappush(heap, (P[i] + Q[j + 1], i, j + 1)) # the next partner of P[i]
def schroeppel_shamir(a, target):
"""Is there a subset with sum target? O(2^(n/2) log n) time, O(2^(n/4)) memory."""
k = len(a) // 4
A, B, C, D = (subset_sums(q) for q in (a[:k], a[k:2*k], a[2*k:3*k], a[3*k:]))
up = ascending_pair_sums(A, B) # A + B, smallest first
down = (-s for s in ascending_pair_sums([-c for c in reversed(C)], [-d for d in reversed(D)]))
x, y = next(up, None), next(down, None) # C + D, largest first
while x is not None and y is not None:
if x + y == target:
return True
if x + y < target:
x = next(up, None)
else:
y = next(down, None)
return FalseThe decreasing stream negates and and reuses the increasing one. Reuses subset_sums from above; checked against brute force on 500 random inputs.
For four decades nothing beat this pair of bounds in the worst case. Nederlof and Węgrzycki (STOC 2021) finally lowered the memory to while keeping time, through a reduction to the orthogonal vectors problem, and follow-up work has lowered it a little further. On random instances with -bit numbers, the representation technique of Howgrave-Graham and Joux (2010), refined by Becker, Coron and Joux (2011), finds solutions in about time, a heuristic bound: it allows a solution to be split into halves in many ways and keeps only a fraction of them.
The same trick elsewhere
k-SUM. Given lists of numbers, choose one number from each so that the sum is 0. Form all sums of the first lists and of the last , then match: time with sorting, or expected with hashing. For four lists:
from collections import Counter
def count_4sum(A, B, C, D):
"""Number of (i, j, k, l) with A[i] + B[j] + C[k] + D[l] == 0: O(n^2) expected time."""
ab = Counter(a + b for a in A for b in B) # every pair sum of the first two lists
return sum(ab[-(c + d)] for c in C for d in D)Compare with 3SUM & the k-SUM Problem, where two pointers solve 3SUM in . Is optimal? Erickson (1995) proved for k-linear decision trees, whose every test is the sign of a linear combination of at most inputs. Yet Kane, Lovett and Moran (STOC 2018) solve k-SUM with linear decision trees of depth when a test may combine inputs. A lower bound is a statement about its model.
Discrete logarithms. Given a prime , a base and , find with . Write with : store the "baby steps" , then take "giant steps" until one lands in the table. This is Shanks's baby-step giant-step algorithm (1971): time and memory instead of .
from math import isqrt
def discrete_log(g, h, p):
"""Smallest x >= 0 with g^x = h (mod p), p prime, or None. O(sqrt(p)) time and memory."""
m = isqrt(p - 1) + 1 # x = i*m + j with 0 <= i, j < m
baby, e = {}, 1
for j in range(m): # baby steps: g^j -> j
baby.setdefault(e, j)
e = e * g % p
giant = pow(g, -m, p) # g^(-m) mod p (Python 3.8+)
y = h
for i in range(m): # giant steps: h * g^(-i*m)
if y in baby:
return i * m + baby[y]
y = y * giant % p
return NoneTested on 200 random exponents modulo the prime 1,000,003, where it stores 1,001 baby steps instead of trying up to a million exponents.
Bidirectional search. A breadth-first search from both ends of a shortest path, stopped when the two frontiers touch, explores about states instead of (see Implicit Graphs & BFS Variants).
Double encryption. Encrypting twice with two independent 56-bit keys, , looks like a 112-bit key. Given a known plaintext–ciphertext pair, encrypt under all keys and store the results, then decrypt under every and look each result up: about cipher operations and memory find the candidate key pairs, and a second known pair weeds out the false matches (Diffie & Hellman, 1977). This is why DES was strengthened to triple DES rather than double DES.
| Problem, in brief | How the halves meet | Cost |
|---|---|---|
| Count the subsets of numbers with sum at most | sort both halves' sums; a pointer moving down the right list counts partners for each left sum | after sorting |
| Four lists of up to 4,000 numbers: count quadruples with sum 0 | hash all pair sums of two lists, look up the other two | expected |
| Knapsack with items and weights up to | each half as (weight, value) pairs sorted by weight, with prefix maxima of value on the right | |
| Paths moving right or down across a grid whose XOR of cells equals | meet on the anti-diagonal: for each diagonal cell, a dictionary counting the XORs of the half-paths that reach it | half-paths from each corner, instead of paths |
You must decide whether some subset of positive integers, each up to , sums to exactly . Which approach fits?
- Dynamic programming over all sums from 0 to
- Meet in the middle: two lists of half-sums, sorted and matched
- Backtracking over all subsets with the "sum exceeds " prune
- Greedy: take the largest numbers that still fit
Show the answer
B. Meet in the middle: two lists of half-sums, sorted and matched
Each half has subset sums: sorting and a two-pointer scan take milliseconds. The values are far too large for a table over sums, and the prune leaves subsets in the worst case.
Key takeaways
- Meet in the middle splits choices into two halves, enumerates the partial results of each, and joins them by sorting, two pointers or hashing: subset sum in instead of (Horowitz & Sahni, 1974), whatever the size of the numbers.
- Merging builds sorted subset-sum lists in time linear in their length, and the two-pointer join discards one element per step without ever discarding half of a match.
- Schroeppel and Shamir keep time with memory by streaming pair sums from heaps (); beating time on worst-case instances is open, while random instances fall to about heuristically.
- The same split powers k-SUM in (optimal only for -linear decision trees), baby-step giant-step discrete logarithms in , bidirectional search, and the attack on double DES.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the two-pointer join, is scanned upward and downward. At some moment . Which move is safe, and why?
- Move to the next : the current is too small
- Move to the next : is the largest sum still in , so no remaining element of can complete
- Move both pointers: neither element can be part of a solution
- Restart the scan of from its largest element
Show the answer
B. Move to the next : is the largest sum still in , so no remaining element of can complete
Every remaining gives , so has no partner left and can be discarded. The current might still pair with a larger , so it must stay.
For numbers, Horowitz and Sahni store two lists of sums. About how many entries does Schroeppel and Shamir's algorithm keep in memory?
Show the answer
B.
Four quarter-lists of sums each, plus two heaps with one entry per element of and of : . The time stays about heap operations, so , on the trade-off curve.
Erickson proved an lower bound for k-SUM, matching meet in the middle. For which algorithms does it hold?
- For every algorithm on a word RAM
- For linear decision trees whose tests each involve at most of the inputs
- For comparison sorts
- For algorithms that use polynomial memory
Show the answer
B. For linear decision trees whose tests each involve at most of the inputs
The bound is for -linear decision trees. When a test may combine inputs, Kane, Lovett and Moran (2018) need only tests, so the lower bound does not extend to all algorithms; for general algorithms only conjectures, such as the 3SUM conjecture, remain.
Why does encrypting twice with two independent 56-bit DES keys give far less than 112 bits of security against an attacker who knows a few plaintext–ciphertext pairs?
- Because DES encryptions compose into a single DES encryption
- Because the attacker can meet in the middle: about cipher operations and memory
- Because the second key can be derived from the first
- It does not: double encryption gives the full 112 bits
Show the answer
B. Because the attacker can meet in the middle: about cipher operations and memory
Encrypt the plaintext under every first key, store the results, then decrypt the ciphertext under every second key and look for a match. The work is about twice that of breaking single DES, not times more, which is why triple DES was adopted instead.
Further reading
- E. Horowitz & S. Sahni, "Computing partitions with applications to the knapsack problem," Journal of the ACM 21(2) (1974), 277–292.
- R. Schroeppel & A. Shamir, "A , algorithm for certain NP-complete problems," SIAM Journal on Computing 10(3) (1981).
- W. Diffie & M. E. Hellman, "Exhaustive cryptanalysis of the NBS Data Encryption Standard," Computer 10(6) (1977), 74–84.
- J. Nederlof & K. Węgrzycki, "Improving Schroeppel and Shamir's algorithm for subset sum via orthogonal vectors," Proceedings of STOC (2021), 1670–1683.
- A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 5, "Complete search", on meet in the middle.