Sub topic 15
Meet in the Middle for Few Items and Huge Capacities
The weight-indexed table from earlier chapters takes O(nW) time. That is fine when the capacity W is a few million. When the weights are measured in nanograms, bytes or cents and W reaches 10^12, no table of that size fits in memory. Value-indexed DP works only when the values are small. If both weights and values are huge but there are only a few dozen items, a different idea works: split the items into two halves, solve each half by brute force, and combine the two halves cleverly.
This chapter assumes you know the 0/1 knapsack problem statement, the brute-force subset enumeration from the earlier chapter, Big-O notation, sorting, and binary search (Python's bisect module).
The Core Idea
Brute force examines all 2^n subsets. For n = 40 that is about 1.1 × 10^12 subsets, far too many. Meet in the middle, published by Horowitz and Sahni in 1974, uses this observation: every subset of the full item list is a subset of the first half joined with a subset of the second half.
- Split the items into a left half A and a right half B of about n/2 items each.
- List every subset of A as a (weight, value) pair. Do the same for B. Each list has about 2^(n/2) entries, which is roughly 10^6 for n = 40.
- For each left subset with weight wL ≤ W, find the most valuable right subset whose weight is at most W − wL.
- The answer is the best total over all left subsets.
Step 3 decides the running time. A scan of the whole right list for every left subset would cost 2^(n/2) × 2^(n/2) = 2^n, which is no better than brute force. To do better, preprocess the right list once so that each query takes logarithmic time.
Pruning Dominated Subsets
Sort the right list by weight. A pair (w, v) is dominated if some other pair weighs no more and is worth at least as much. A dominated pair can never be the best answer to a query, so you can throw it away. After pruning, the surviving pairs have increasing weights and increasing values, like a staircase. On a staircase, the best pair with weight ≤ r is simply the last pair with weight ≤ r. Binary search finds it in O(log 2^(n/2)) = O(n) time.
Pruning takes one pass over the sorted list. Keep a running best value and keep a pair only if its value beats that best.
Implementation
from bisect import bisect_right
from itertools import product
import random
def subset_sums(items):
# items: list of (value, weight); returns (weight, value) for every subset
sums = [(0, 0)]
for v, w in items:
sums += [(sw + w, sv + v) for sw, sv in sums]
return sums
def knapsack_mitm(values, weights, capacity):
items = list(zip(values, weights))
half = len(items) // 2
left = subset_sums(items[:half])
right = subset_sums(items[half:])
# Build the staircase: weights increasing, values strictly increasing
right.sort()
stair_w, stair_v = [], []
best = -1
for w, v in right:
if w > capacity:
break
if v > best:
best = v
stair_w.append(w)
stair_v.append(v)
answer = 0
for w, v in left:
if w > capacity:
continue
j = bisect_right(stair_w, capacity - w) - 1 # j >= 0: (0, 0) is always kept
answer = max(answer, v + stair_v[j])
return answer
def knapsack_brute(values, weights, capacity):
best = 0
for mask in product([0, 1], repeat=len(values)):
w = sum(wi for wi, m in zip(weights, mask) if m)
if w <= capacity:
best = max(best, sum(vi for vi, m in zip(values, mask) if m))
return best
print(knapsack_mitm([60, 100, 120], [10, 20, 30], 50)) # 220
# Huge weights: a weight-indexed table would need about 10^12 cells
random.seed(1)
for _ in range(200):
n = random.randint(0, 12)
vals = [random.randint(1, 10**9) for _ in range(n)]
wts = [random.randint(1, 10**12) for _ in range(n)]
cap = random.randint(0, 3 * 10**12)
assert knapsack_mitm(vals, wts, cap) == knapsack_brute(vals, wts, cap)
print("all random tests passed")On the small example the left half is item 0, which gives the pairs (0, 0) and (10, 60). The right half holds items 1 and 2, which give (0, 0), (20, 100), (30, 120) and (50, 220). The left pair (0, 0) has 50 units of capacity left and picks (50, 220). The left pair (10, 60) has 40 left and picks (30, 120), for a total of 180. The answer is 220, which matches the DP chapters.
The subset_sums line sums += [...] is safe. Python builds the new list from the current sums before it extends sums, so each item doubles the list exactly once.
Complexity
| Step | Time | Space |
|---|---|---|
| Enumerate both halves | O(2^(n/2)) | O(2^(n/2)) |
| Sort the right half | O(2^(n/2) · n) | O(2^(n/2)) |
| Prune | O(2^(n/2)) | O(2^(n/2)) |
| Query every left subset | O(2^(n/2) · n) | O(1) extra |
| Total | O(n · 2^(n/2)) | O(2^(n/2)) |
None of these costs depends on W or on the sizes of the values. That is the reason to use this method. A capacity of 10^18 costs the same as a capacity of 50.
You can drop the log factor in two ways. You can generate each half's sums already sorted by merging, the way merge sort combines lists, so no separate sort is needed. You can also sort the left list by weight and then sweep the staircase with a pointer that only moves backward, instead of running a binary search for each query. Both change the constant factor more than the overall picture.
Gotchas and Edge Cases
- Memory, not time, sets the limit. For n = 40 each half has 2^20 ≈ 1,048,576 pairs. In CPython a tuple of two ints takes roughly 100 bytes, so one half uses around 100 MB. At n = 50 each half has 2^25 ≈ 33 million pairs, which is impractical in pure Python. Parallel
arrayor NumPy arrays cut memory several-fold. The Schroeppel–Shamir variant reduces memory to O(2^(n/4)) at the cost of more complex code. - Do not skip pruning. Without the staircase, the last pair with weight ≤ r is not necessarily the most valuable one. The search then returns wrong answers without raising any error.
- Equal weights. Sorting tuples orders ties by value, so the most valuable pair at a given weight comes last. The
v > besttest keeps it, andbisect_rightlands on it. - Tiny inputs. If n is 0 or 1, one half is empty, and
subset_sums([])returns[(0, 0)]. The code needs no special case. - Capacity 0. Only weight-0 subsets survive, and the empty subset gives 0. Zero-weight items are handled correctly as well.
- Unbalanced splits. An odd n puts the extra item in the right half. Put it on the side whose list you can afford to keep in memory.
When to Choose It
| Instance shape | Good choice |
|---|---|
| n up to a few thousand, W up to about 10^7 | Weight-indexed DP |
| Small total value, huge W | Value-indexed DP |
| n ≤ about 40, W and values arbitrary | Meet in the middle |
| n large, both W and values huge, exact answer needed | Branch and bound |
| n large, near-optimal answer is enough | FPTAS |
Meet in the middle guarantees its running time in the worst case. Branch and bound is often faster on real data, but adversarial inputs can push it to exponential time in n, and it gives no promise in advance.
Exercise
You have 36 items with weights up to 10^15 and capacity 10^16. Estimate how many subset pairs meet in the middle stores and how many binary-search queries it runs, and compare with plain brute force and with a weight-indexed table.
Show answer
Each half has 18 items, so each list has 2^18 = 262,144 pairs. The algorithm stores at most that many staircase pairs and runs 262,144 queries, each about 18 comparisons, which is roughly 5 million steps. Brute force checks 2^36 ≈ 6.9 × 10^10 subsets. A weight-indexed table would need 36 × 10^16 cells, which is impossible.
Exercise
Suppose you delete the pruning loop and run bisect_right directly on the sorted right list. Give a right list on which a query with remaining capacity 30 returns the wrong value.
Show answer
Take the right pairs (0, 0), (20, 100) and (30, 10). The last pair with weight ≤ 30 is (30, 10), so the query returns value 10. The correct best is 100 from (20, 100). Pruning removes (30, 10) because it is heavier than (20, 100) and worth less.
Exercise
Why does the bound on the query index j never fall below 0 when the left weight is at most the capacity?
Show answer
The empty subset (0, 0) is always in the right list. It comes first after sorting, and the pruning loop keeps it because 0 > -1. Since capacity − wL ≥ 0, bisectright returns at least 1, so j is at least 0.