Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Algorithms · Exponential Search

Meet in the Middle.

Does any subset of these numbers add up to the target? Trying every subset is 2ⁿ — hopeless past ~30 items. But split the set in two, enumerate each half’s subset sums separately, and the two halves can shake hands: for every sum on the left, look for its complement on the right. Exponential work becomes its own square root — 2ⁿ → 2·2^(n/2).

O(2^(n/2)) time · square-root speedup · subset-sum
split in two

Halve the set; solve each half independently.

half-sums

Enumerate all 2^(n/2) subset sums of each half.

complement

For a left sum s, seek target − s among the right sums.

handshake

A left subset + a right subset that together hit the target.

mitm.js — enumerate halves, match complements
target sum: 9 16 21 100
Ready
The set is split into a left and right half. We list every subset sum of each. Press Step: for each left sum s, we look for target − s in the right sums — a match means a subset hits the target.
–
left sum s
–
need t−s
–
vs brute 2ⁿ

How it works

The problem is exponential because a subset is a yes/no choice per item — 2ⁿ combinations. The trick: those choices split cleanly. Whatever the left half contributes, the right half must contribute exactly target − (left sum). So you never need to pair every left subset with every right subset (that would be 2ⁿ again) — you just look up the needed complement.

1

Split the set in half

n items → two halves of n/2. Each half has only 2^(n/2) subsets — exponentially fewer.

2

Enumerate each half’s sums

List all subset sums of the left half and all of the right half. Store the right sums in a hash set (or sort them).

3

Match complements

For each left sum s, check if target − s is a right sum. A hit means left-subset + right-subset = target.

✓

Square-root win

Total work ≈ 2·2^(n/2) instead of 2ⁿ. For n = 40: ~10⁶ vs ~10¹² — a million times faster.

Time
O(2^(n/2))
Brute force
O(2ⁿ)
Space
O(2^(n/2))
Match
hash / binary search

The code

# does any subset of a sum to the target? O(2^(n/2)) def subset_sums(items): sums = [0] for x in items: sums += [s + x for s in sums] # double each item return sums def can_hit(a, target): mid = len(a) // 2 left = subset_sums(a[:mid]) right = set(subset_sums(a[mid:])) # hash for O(1) lookup return any((target - s) in right for s in left)

The same idea generalizes: 4-sum becomes two 2-sums, some knapsack variants split this way, and password/hash search meets from both ends. The rule of thumb — reach for meet-in-the-middle when a problem is 2ⁿ but n ≤ ~40 and the search splits into two combinable halves.

Quick check

1. Why is meet-in-the-middle O(2^(n/2)) and not O(2ⁿ)?

2. When is meet-in-the-middle the right tool?

FAQ

What is meet in the middle?

A technique that splits an exponential search into two halves, solves each, and combines them by matching partial results — turning 2ⁿ work into about 2·2^(n/2).

How does it solve subset-sum?

Enumerate the subset sums of each half, store one half in a hash set, and for each sum in the other half check whether target minus it exists in the set.

How big can n be?

Comfortably up to about 40, where 2^(n/2) ≈ 10⁶ is fast but 2^40 ≈ 10¹² is not. Beyond that, even the half is too large.

What else uses it?

4-sum (two 2-sums), partition problems, some knapsack variants, and cryptographic/hash search that meets from both ends.

The picture: two short lists instead of one long one

left sumsright sums0need 93need 634need −2537need −284need 57need 238need −2941need −320125172147194 + 5 = 9 and 7 + 2 = 9: two handshakes, both found by lookup
Set [3, 34, 4, 12, 5, 2], target 9, split after three items. Each half has 2³ = 8 subset sums. Highlighted boxes are the two matched pairs; every other left sum asks for a number the right list does not contain.

Worked example, step by step

Take A = [3, 34, 4, 12, 5, 2] and target 9. Split into left [3, 34, 4] and right [12, 5, 2]. The right half’s sums go in a hash set: {0, 12, 5, 17, 2, 14, 7, 19}. Then for each left subset sum s, look up 9 − s.

Left subsets9 − sLookup
{}09not in right list
{3}36not in right list
{34}34−25not in right list
{3,34}37−28not in right list
{4}45in right list
{3,4}72in right list
{34,4}38−29not in right list
{3,34,4}41−32not in right list

The scan makes 8 lookups and finds 2 matches: {4} + {5}, and {3,4} + {2}. Enumerating all 2⁶ = 64 subsets directly finds the same 2. Look at the rows that fail: 34 and everything built on it ask for negative numbers, which can never be a sum of positive items. A sorted right list lets you stop early on those; a hash set simply answers no. The work here was 8 + 8 sums plus 8 lookups instead of 64 subsets, and the gap grows exponentially: at n = 40 the brute force is 2⁴⁰ = 1,099,511,627,776 subsets, while the two halves hold 2²⁰ = 1,048,576 sums each, about 2,097,152 sums in total.

When there is no exact hit. A common variant asks for the largest subset sum that does not exceed the target. A hash set cannot answer “the biggest value ≤ x”, so sort the right sums instead: [0, 2, 5, 7, 12, 14, 17, 19]. For target 13, each left sum s takes the largest right sum ≤ 13 − s by binary search. s = 0 takes 12; s = 3 takes 7, for 10; s = 4 takes 7, for 11; s = 7 takes 5, for 12; and 34 and up find nothing. The best is 12, reached twice ({12} alone, and {3, 4} + {5}), and no subset hits 13 exactly. Sorting costs O(2n/2 · n) once, and each lookup is a binary search.

Complexity and trade-offs

CaseTimeSpaceWhy
Meet in the middleO(2n/2) with a hash set; O(n · 2n/2) if you sortO(2n/2)Two lists of 2n/2 sums, one lookup per left sum.
Brute force over subsetsO(2n)O(n) or O(1)Every subset is one yes/no choice per item. About 10¹² at n = 40.
Pseudo-polynomial DPO(n · T)O(T)Fast when the target T is small, useless when values are around 10¹⁵.
Left list only, no hashO(2n/2 · 2n/2)O(2n/2)Pairing every left with every right is 2ⁿ again. The lookup is what saves you.

The price is memory. Each half is 2n/2 integers, so at n = 40 that is about 1M entries per half, roughly 8 MiB of 8-byte sums per list before hash overhead. At n = 60 the time would still be 2·2³⁰ and the memory would be gigabytes, which is where this method runs out. Choose it when n is around 30 to 45, values are too large for the DP, and the problem decomposes into two independent halves.

Common mistakes

  • Pairing instead of looking up

    Writing a double loop over left sums and right sums, checking l + r == target, is O(2n/2 · 2n/2) = O(2ⁿ). The whole method is that the right side is a hash set or sorted array and the left side does target − s.

  • Forgetting the empty subset

    Start each half’s sums at [0]. Without it, a target reachable by items from only one half (for example 12 alone) is never found, because there is no empty partner on the other side.

  • Splitting unevenly by accident

    a[:n//2] and a[n//2:] are right. Splitting 10 and 30 leaves a 2³⁰ list and you have lost the square-root saving.

  • Counting subsets with a set

    To count subsets that hit the target, a hash set of right sums is wrong: duplicate sums collapse. Use a counter keyed by sum, then add count[target − s] for each left sum.

  • Overflow on large values

    Sums of 40 values near 10¹⁸ overflow a 64-bit integer. Use a wider type, or prune any partial sum that already exceeds the target when the items are non-negative.

Where this shows up

  • Subset-sum and knapsack at moderate n

    Horowitz and Sahni (1974) used exactly this split for the knapsack problem, getting O(2n/2) time. It is still the standard answer when n is about 40 but the weights are huge.

  • Cryptanalysis of double encryption

    Encrypting twice with two independent keys looks like it squares the work. A meet-in-the-middle attack encrypts forward with every key from one side and decrypts backward with every key from the other, then matches the middle value. This is why double DES gives far less than twice the key strength, and why triple DES was used instead.

  • Discrete logarithms

    Baby-step giant-step finds x in gx = h in about √n steps by storing one list of powers and matching a second against it, the same handshake.

  • k-sum problems

    4-sum becomes two 2-sums: hash every pair sum, then look up the complement of each pair. That turns O(n⁴) into O(n²) expected time.

SOLVE IT YOURSELF

Solve it: halve the exponent

Checking all 2⁴⁰ subsets is hopeless. Checking 2²⁰ of them twice and joining the halves is a million operations. The problem stays exponential — the exponent just halves. Python or TypeScript.

YOUR TASK

Implement count_subsets(nums, target): count how many subsets sum to exactly target. Split the input in half, enumerate each half separately, and join — do not enumerate all 2ⁿ subsets.

HINTS — 6 IDEAS
  1. Split the list in two. Enumerate every subset sum of the left half into a frequency map — 2^(n/2) entries.
  2. Enumerate every subset sum of the right half. For each sum s, the left half must supply target − s.
  3. Add the count of that value from the map, not 1 — several different left subsets can share a sum, and each pairs with this right subset.
  4. Total work is 2·2^(n/2) instead of 2ⁿ. At n = 40 that is roughly two million instead of a trillion.
  5. The empty subset (sum 0) must be included in both halves — that is what lets an answer come entirely from one side.
  6. Iterating mask from 0 to 2^half − 1 and testing bits gives exactly the right enumeration, empty subset included.
CPython · WebAssembly

Keep going

Finished this one? 0 / 99 Algorithms done
NextCounting a Crowd in Kilobytes: HyperLogLog Next in “Advanced Algorithms & Data Structures” · step 12 of 13

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Algorithms