π WAYPOINT LESSON
Meet in the Middle
βββ advancedβ³ 30 min readπ Lesson 124 of 281
Halve exponential search: enumerate each half separately and join the results in a searchable structure.
Meet in the Middle
Exhaustive search dies at n β 25 because 2^n explodes. Split the items into two halves: enumerate each half (2^(n/2) each), then join the two lists with sorting + binary search or a hash table. For n = 30 that is about 10^4β10^5 operations β feasible where 2^30 β 10^9 is not.
Worked problem β count subsets of 30 items with weight sum exactly S:
- Enumerate all subset sums of the first 15 items (~32768 values).
- Enumerate all subset sums of the last 15 items.
- Sort one list; for every sum x in the other list, count occurrences of S β x with binary search (or a hash map in one pass).
Complexity: O(2^(n/2) Β· n/2) time, O(2^(n/2)) memory β the memory line is the real engineering limit on the sandbox.
Recognition cues: n β€ 40, a "pick some items" objective, no polynomial structure in sight. If n β€ 20 plain 2^n enumeration already fits.