Skip to the workspace
Pebellslearn by building
Monotonic Structures & Search on the Answer  ›  Lesson

Meet in the Middle

Meet in the Middle 32 minSplit an exponential search in half, then join the halves with sorting or hashing

dsa / Meet in the Middle

Explore each scene at your own pace.

01 · Split, enumerate, join

Split, enumerate, join

Meet in the Middle

Definition
Meet in the middle splits a problem over n items into two halves, lists every subset total for each half separately, and combines them with sorting and binary search. It cuts 2ⁿ work down to roughly its square root, at the cost of memory.
In plain words
Instead of trying every outfit from forty items at once, work out every combination for the first twenty, do the same for the last twenty, then match pairs. Two lists of a million entries beat one list of a trillion.

In short: when a search space is every subset of n items, trying all 2ⁿ is hopeless past about n = 40 — but every subset is exactly one subset of the left half paired with one subset of the right half. Enumerate each half's subset sums on its own (2^(n/2) of them), sort one half, and for each sum in the other half, one binary search finds its best partner. That turns a trillion into about a million: the square root of the search space, traded for memory instead of time.

Left half {7, 13} enumerated to sums 0, 7, 13, 20 and right half {22, 31} to 0, 22, 31, 53: for right sum 31, the best left partner at or under 50−31=19 is 13, giving 44

When Quarry restarts, it warms its cache by preloading index segments from disk, so the first queries don't all miss. The cache has a fixed budget in bytes, and each segment has a size. The warmer wants the set of segments that fills the budget as fully as possible without going over. A fuller cache means fewer cold reads.

python

That's fine for four segments. A real index has about forty, and 2⁴⁰ is roughly a trillion subsets. The knapsack table from the dynamic programming lessons doesn't rescue you either, because it needs one column per byte of budget, and a cache budget is tens of billions of bytes. Backtracking with pruning helps on friendly inputs, but its worst case is still all 2⁴⁰ subsets.

Meet in the middle gets you to about 2²⁰ work, a million instead of a trillion, with an idea that sounds too simple to work.

Split, enumerate, join

Cut the segments into two halves. Every subset of all the segments is exactly one subset of the left half together with one subset of the right half, and its total is the left total plus the right total. So:

  1. Enumerate every subset sum of the left half, and sort them.
  2. Enumerate every subset sum of the right half.
  3. Join: for each right sum r, the best partner is the largest left sum that is at most budget - r. In a sorted list, that's one binary search.

With 40 segments, each half has 2²⁰ ≈ one million sums. Sorting one half and running a million binary searches costs about 2²⁰ × 20 steps, around twenty million, where brute force needed a trillion.

Enumerating a half is easiest by doubling: start from [0], and for each item, keep every sum you have and add a copy with the item included.

step through it
1items = [3, 5, 9]
2sums = [0]
3for x in items:
4 sums = sums + [s + x for s in sums]
5print(sorted(sums))

Here is the same enumeration as a decision tree. Each level decides one item: the left branch skips it and the right branch takes it. The leaves are the half's subset sums, and there are exactly 2³ = 8 of them.

watch it move · tree

One half of the search. Each level doubles the sums, so a half of n/2 items has 2^(n/2) leaves. Both halves together hold far fewer sums than the full tree.

Nothing chosen yet, so the sum is 0. Binary tree, 15 nodes, height 4. At node 0.

1 / 5

The full tree over six items would have 64 leaves. The two half-trees have 8 each.

What does this print?
def subset_sums(items):
    sums = [0]
    for x in items:
        sums = sums + [s + x for s in sums]
    return sums

sizes = [7, 13, 22, 31, 18, 9]
left = subset_sums(sizes[:3])
right = subset_sums(sizes[3:])
print(len(left), len(right), len(left) * len(right))
Scene 1 of 12
Project context and further resources
You're building a piece ofQuarry — the query planner
This piece — best_warm_set(): The fullest set of index segments that fits the warm cache, found without trying every set.
Scenario Quarry restarts with a cold cache and a byte budget. The cache warmer picks the set of index segments that fills the budget most fully, checking about a million half-sets instead of a trillion full ones.
best_warm_set.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
best_warm_set(sizes, budget) → intThe largest total of a set of segments that fits in the budget.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.