Simple Algorithm
Algorithms & Data Structures · Optimal · 26 min

Meet in the Middle

Split the search into halves: 2^(n/2) for subset sum and more.

Subset sum on 40 numbers means 240≈1.1×10122^{40} \approx 1.1 \times 10^{12} subsets: about three hours at 10810^8 per second. Split the numbers into two halves of 20 and list each half's 220=1,048,5762^{20} = 1{,}048{,}576 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 O(2n/2)O(2^{n/2}) 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 O(2n/4)O(2^{n/4})-memory algorithm and the trade-off T⋅S2=O(2n)T \cdot S^2 = O(2^n), and state what is known about beating 2n/22^{n/2}.
  • 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 nn binary choices visits up to 2n2^n 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, 2⋅2n/22 \cdot 2^{n/2} partial solutions in all, and matched.

For subset sum, with numbers a0,…,an−1a_0, \dots, a_{n-1} and target TT: list the sums LL of all subsets of the first half and RR of the second half, sort them, and look for ℓ∈L\ell \in L and r∈Rr \in R with ℓ+r=T\ell + r = T.

HalfIts subset sums, sorted
{2,3,4}\{2, 3, 4\}0, 2, 3, 4, 5, 6, 7, 9
{5,7,9}\{5, 7, 9\}0, 5, 7, 9, 12, 14, 16, 21
Pairs with sum 120 + 12 = {5, 7}; 3 + 9 = {3, 9}; 5 + 7 = {2, 3, 7}; 7 + 5 = {3, 4, 5}
The numbers 2, 3, 4, 5, 7, 9 with target 12: two lists of 23=82^3 = 8 sums replace 26=642^6 = 64 subsets, and the four matching pairs are exactly the four solutions.
python
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 10910^9, counting the subsets that hit a target took about one second in CPython.

Predict before you look

With the rule of thumb of 10810^8 simple operations per second, about how many seconds does the brute force over all 2402^{40} subsets take, at one operation per subset?

Show the answer

11000 s

240≈1.1×10122^{40} \approx 1.1 \times 10^{12}, and 1.1×1012/108=11,0001.1 \times 10^{12} / 10^8 = 11{,}000 seconds, about three hours, before even counting the work per subset. Meet in the middle handles 2⋅220≈2.1×1062 \cdot 2^{20} \approx 2.1 \times 10^6 sums plus sorting and matching: milliseconds in a compiled language.

Why it is correct, and how fast

DerivationProof
  1. ∑i=1kO(2i)  =  O(2k),k=⌈n/2⌉\sum_{i=1}^{k} O(2^{i}) \;=\; O(2^{k}), \qquad k = \lceil n/2 \rceil

    Sorted lists in linear time. Let LiL_i be the sorted subset sums of a0,…,ai−1a_0, \dots, a_{i-1}. A subset of the first i+1i+1 numbers either omits aia_i or contains it, so Li+1L_{i+1} is the merge of two sorted lists of length 2i2^i, which costs O(2i+1)O(2^{i+1}); over all i≤ki \le k the costs form a geometric series:

  2. ∣L∣+∣R∣  ≤  2⌈n/2⌉+2⌊n/2⌋  =  O(2n/2) steps\abs{L} + \abs{R} \;\le\; 2^{\lceil n/2 \rceil} + 2^{\lfloor n/2 \rfloor} \;=\; O(2^{n/2}) \text{ steps}

    The two-pointer join. Scan LL upward from its smallest element and RR downward from its largest. If ℓ+r<T\ell + r < T, then ℓ\ell cannot pair with rr, the largest sum left in RR, nor with anything smaller, so discard ℓ\ell; if ℓ+r>T\ell + r > T, discard rr 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

  3. { S:∑Sa=T }  ⟷  { (SL,SR):Σ(SL)+Σ(SR)=T }\{\,S : \textstyle\sum_{S} a = T\,\} \;\longleftrightarrow\; \{\,(S_L, S_R) : \Sigma(S_L) + \Sigma(S_R) = T\,\}

    Counting and bounds. Counting needs multiplicities of equal sums, so a binary search into RR for each ℓ\ell, as in the code, costs a factor log⁡∣R∣=O(n)\log \abs{R} = O(n). For "the largest sum at most WW", the same downward pointer gives each ℓ\ell its best partner. Each of the 2n2^n subsets is a pair, so nothing is missed:

The idea in one sentence: the search tree has 2n2^n 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 101810^{18}. That is the difference from the pseudo-polynomial dynamic program over sums, O(n⋅T)O(n \cdot T) (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 n=80n = 80 each half has 2402^{40} sums, terabytes of them. Schroeppel and Shamir (1981) split the numbers into four quarters A,B,C,DA, B, C, D instead, with sorted subset-sum lists of 2n/42^{n/4} entries each. The join still needs all 2n/22^{n/2} sums a+ba + b in increasing order and all sums c+dc + d 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 AA produces the sums a+ba + b in increasing order: pop the smallest ai+bja_i + b_j, push ai+bj+1a_i + b_{j+1}. That is a ∣A∣\abs{A}-way merge of sorted lists, with 2n/42^{n/4} heap entries.

python
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 False

The decreasing stream negates CC and DD 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 O∗(20.249999n)O^*(2^{0.249999n}) while keeping O∗(2n/2)O^*(2^{n/2}) time, through a reduction to the orthogonal vectors problem, and follow-up work has lowered it a little further. On random instances with nn-bit numbers, the representation technique of Howgrave-Graham and Joux (2010), refined by Becker, Coron and Joux (2011), finds solutions in about 20.291n2^{0.291n} 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 kk lists of nn numbers, choose one number from each so that the sum is 0. Form all sums of the first ⌈k/2⌉\lceil k/2 \rceil lists and of the last ⌊k/2⌋\lfloor k/2 \rfloor, then match: O(n⌈k/2⌉log⁡n)O(n^{\lceil k/2 \rceil} \log n) time with sorting, or expected O(n⌈k/2⌉)O(n^{\lceil k/2 \rceil}) with hashing. For four lists:

python
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 O(n2)O(n^2). Is n⌈k/2⌉n^{\lceil k/2 \rceil} optimal? Erickson (1995) proved Ω(n⌈k/2⌉)\Omega(n^{\lceil k/2 \rceil}) for k-linear decision trees, whose every test is the sign of a linear combination of at most kk inputs. Yet Kane, Lovett and Moran (STOC 2018) solve k-SUM with linear decision trees of depth O(nlog⁡2n)O(n \log^2 n) when a test may combine 2k2k inputs. A lower bound is a statement about its model.

Discrete logarithms. Given a prime pp, a base gg and hh, find xx with gx≡h(modp)g^x \equiv h \pmod p. Write x=i m+jx = i\,m + j with m=⌈p−1 ⌉m = \lceil \sqrt{p-1}\,\rceil: store the mm "baby steps" gjg^j, then take "giant steps" h⋅g−imh \cdot g^{-im} until one lands in the table. This is Shanks's baby-step giant-step algorithm (1971): O(p)O(\sqrt p) time and memory instead of O(p)O(p).

python
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 None

Tested 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 2bd/22 b^{d/2} states instead of bdb^d (see Implicit Graphs & BFS Variants).

Double encryption. Encrypting twice with two independent 56-bit keys, c=Ek2(Ek1(m))c = E_{k_2}(E_{k_1}(m)), looks like a 112-bit key. Given a known plaintext–ciphertext pair, encrypt mm under all 2562^{56} keys k1k_1 and store the results, then decrypt cc under every k2k_2 and look each result up: about 2572^{57} cipher operations and 2562^{56} 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 briefHow the halves meetCost
Count the subsets of n≤40n \le 40 numbers with sum at most SSsort both halves' sums; a pointer moving down the right list counts partners for each left sumO(2n/2)O(2^{n/2}) after sorting
Four lists of up to 4,000 numbers: count quadruples with sum 0hash all 1.6×1071.6 \times 10^7 pair sums of two lists, look up the other twoO(n2)O(n^2) expected
Knapsack with n=40n = 40 items and weights up to 101510^{15}each half as (weight, value) pairs sorted by weight, with prefix maxima of value on the rightO(n⋅2n/2)O(n \cdot 2^{n/2})
Paths moving right or down across a 20×2020 \times 20 grid whose XOR of cells equals kkmeet on the anti-diagonal: for each diagonal cell, a dictionary counting the XORs of the half-paths that reach it2192^{19} half-paths from each corner, instead of (3819)≈3.5×1010\binom{38}{19} \approx 3.5 \times 10^{10} paths
Signals: nn between about 30 and 45 (too many for 2n2^n, enough for 2n/22^{n/2}, by the rule of thumb), a choice per element, an objective that adds up (or XORs) across a split, and values too large for a table over sums.
Check your understanding

You must decide whether some subset of n=36n = 36 positive integers, each up to 101510^{15}, sums to exactly TT. Which approach fits?

  1. Dynamic programming over all sums from 0 to TT
  2. Meet in the middle: two lists of 2182^{18} half-sums, sorted and matched
  3. Backtracking over all subsets with the "sum exceeds TT" prune
  4. Greedy: take the largest numbers that still fit
Show the answer

B. Meet in the middle: two lists of 2182^{18} half-sums, sorted and matched

Each half has 218=262,1442^{18} = 262{,}144 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 236≈6.9×10102^{36} \approx 6.9 \times 10^{10} subsets in the worst case.

Key takeaways

  • Meet in the middle splits nn choices into two halves, enumerates the 2n/22^{n/2} partial results of each, and joins them by sorting, two pointers or hashing: subset sum in O(2n/2)O(2^{n/2}) instead of O(2n)O(2^n) (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 O∗(2n/2)O^*(2^{n/2}) time with O(2n/4)O(2^{n/4}) memory by streaming pair sums from heaps (T⋅S2=O(2n)T \cdot S^2 = O(2^n)); beating 2n/22^{n/2} time on worst-case instances is open, while random instances fall to about 20.291n2^{0.291n} heuristically.
  • The same split powers k-SUM in O(n⌈k/2⌉)O(n^{\lceil k/2 \rceil}) (optimal only for kk-linear decision trees), baby-step giant-step discrete logarithms in O(p)O(\sqrt p), bidirectional search, and the 2572^{57} attack on double DES.

Check yourself

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

Question 1

In the two-pointer join, LL is scanned upward and RR downward. At some moment ℓ+r<T\ell + r < T. Which move is safe, and why?

  1. Move to the next rr: the current rr is too small
  2. Move to the next ℓ\ell: rr is the largest sum still in RR, so no remaining element of RR can complete ℓ\ell
  3. Move both pointers: neither element can be part of a solution
  4. Restart the scan of RR from its largest element
Show the answer

B. Move to the next ℓ\ell: rr is the largest sum still in RR, so no remaining element of RR can complete ℓ\ell

Every remaining r′≤rr' \le r gives ℓ+r′≤ℓ+r<T\ell + r' \le \ell + r < T, so ℓ\ell has no partner left and can be discarded. The current rr might still pair with a larger ℓ\ell, so it must stay.

Question 2

For n=64n = 64 numbers, Horowitz and Sahni store two lists of 2322^{32} sums. About how many entries does Schroeppel and Shamir's algorithm keep in memory?

  1. O(232)O(2^{32})
  2. O(216)O(2^{16})
  3. O(28)O(2^{8})
  4. O(64)O(64)
Show the answer

B. O(216)O(2^{16})

Four quarter-lists of 2162^{16} sums each, plus two heaps with one entry per element of AA and of CC: O(2n/4)=O(216)O(2^{n/4}) = O(2^{16}). The time stays about 2322^{32} heap operations, so T⋅S2=232⋅232=264T \cdot S^2 = 2^{32} \cdot 2^{32} = 2^{64}, on the trade-off curve.

Question 3

Erickson proved an Ω(n⌈k/2⌉)\Omega(n^{\lceil k/2 \rceil}) lower bound for k-SUM, matching meet in the middle. For which algorithms does it hold?

  1. For every algorithm on a word RAM
  2. For linear decision trees whose tests each involve at most kk of the inputs
  3. For comparison sorts
  4. For algorithms that use polynomial memory
Show the answer

B. For linear decision trees whose tests each involve at most kk of the inputs

The bound is for kk-linear decision trees. When a test may combine 2k2k inputs, Kane, Lovett and Moran (2018) need only O(nlog⁡2n)O(n \log^2 n) tests, so the lower bound does not extend to all algorithms; for general algorithms only conjectures, such as the 3SUM conjecture, remain.

Question 4

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?

  1. Because DES encryptions compose into a single DES encryption
  2. Because the attacker can meet in the middle: about 2572^{57} cipher operations and 2562^{56} memory
  3. Because the second key can be derived from the first
  4. It does not: double encryption gives the full 112 bits
Show the answer

B. Because the attacker can meet in the middle: about 2572^{57} cipher operations and 2562^{56} memory

Encrypt the plaintext under every first key, store the 2562^{56} 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 2562^{56} 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 T=O(2n/2)T = O(2^{n/2}), S=O(2n/4)S = O(2^{n/4}) 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.