Sub topic 15
Meet in the Middle for Few Items and Huge Capacities
This chapter assumes you know the 0/1 knapsack problem, exhaustive search over subsets, and the O(nW) table from earlier chapters. You also need binary search and sorting in Python.
When the Table Is Useless
The weight-indexed DP needs one cell per capacity value. If the weights are around 10^12, that table cannot fit in memory. Value-indexed DP fails the same way when the values are large too. Brute force over all 2^n subsets works for about 20 items. With 40 items it needs roughly 10^12 subsets, which is too many.
Meet in the middle covers the gap: few items (up to about 40) with arbitrarily large weights and values. It splits the items into two halves and lists every subset of each half, which costs 2^(n/2) per half. It then joins the two lists efficiently instead of trying every pair.
The Join Step
Take a left subset with weight w and value v. The best right subset to pair with it is the one with the highest value among those with weight at most capacity - w. Finding it takes two steps:
- Sort the right subsets by weight.
- Remove dominated entries. A subset is dominated if another subset weighs no more and is worth at least as much. After this pruning, value rises strictly as weight rises, so the heaviest entry that fits is also the most valuable one.
A single bisect_right call then answers each left subset's query in O(log) time.
from bisect import bisect_right
def subsets(items):
# Return (weight, value) for every subset of items
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 = subsets(items[:half])
right = sorted(subsets(items[half:]))
# Keep a staircase: weights ascending, values strictly increasing
ws, vs = [], []
for w, v in right:
if w > capacity:
break
if not vs or v > vs[-1]:
ws.append(w)
vs.append(v)
best = 0
for w, v in left:
if w > capacity:
continue
j = bisect_right(ws, capacity - w) - 1 # ws[0] == 0, so j >= 0
best = max(best, v + vs[j])
return best
print(knapsack_mitm([60, 100, 120], [10, 20, 30], 50)) # 220
T = 10**12
print(knapsack_mitm([10, 7, 8, 3], [6*T, 4*T, 5*T, 2*T], 11*T)) # 18The second call uses a capacity of 11 trillion. A DP table that size could never be allocated, but this method only builds 4 + 4 subset entries.
Cost and Common Errors
| Method | Time | Practical limit |
|---|---|---|
| Brute force | O(2^n · n) | n ≈ 20–25 |
| Meet in the middle | O(2^(n/2) · n) | n ≈ 40 |
| Weight-indexed DP | O(nW) | W ≈ 10^7 |
Memory is O(2^(n/2)). For n = 40 that is about a million entries per half, which is manageable.
Other common mistakes:
- Forgetting the empty subset. It must appear on both sides, or you miss solutions that use items from only one half.
- Not filtering left subsets heavier than the capacity. The search target
capacity - wturns negative and the code reads the wrong entry. - Splitting unevenly. A 10/30 split costs 2^30 work on one side and loses most of the speedup.
Exercise
With n = 36 items, roughly how many subset entries does meet in the middle generate in total, compared with brute force?
Show answer
Each half has 18 items, so it generates 2 × 2^18 ≈ 524,000 entries. Brute force needs 2^36 ≈ 6.9 × 10^10 subsets, about 130,000 times more.
Exercise
Why does the code append a right entry only when its value is strictly greater than the last kept value?
Show answer
An entry that weighs at least as much as the last kept one but is not worth more is dominated. Removing it makes values strictly increasing along the list, so the last entry that fits under the remaining capacity is guaranteed to be the most valuable choice.