Meet in the Middle: Turning 2^n Into 2^(n/2) in Coding Interviews

Constraints are a hint. When a problem says n ≤ 40 and asks about subsets, 2^40 is about a trillion: too slow. But 2^20 is about a million, which is fast. Meet in the middle exploits exactly that gap.

The pattern

  1. Split the items into two halves A and B.
  2. Enumerate every subset of each half (2^(n/2) each) and record what matters, such as the sum.
  3. Combine: for each value from A, find the best matching value from B using sorting with binary search, two pointers or a hash map.

Example: closest subset sum to a target

from bisect import bisect_left

def sums(items):
    out = [0]
    for x in items:
        out += [s + x for s in out]
    return out

def closest_subset_sum(nums, target):
    half = len(nums) // 2
    left, right = sums(nums[:half]), sorted(sums(nums[half:]))
    best = float("inf")
    for s in left:
        need = target - s
        i = bisect_left(right, need)
        for j in (i - 1, i):
            if 0 <= j < len(right):
                best = min(best, abs(s + right[j] - target))
    return best

Complexity: O(2^(n/2) · n) time and O(2^(n/2)) memory, versus O(2^n) for plain brute force.

Variations worth knowing

Pitfalls

Interview framing: "n is 40, so I'll split into two halves of 20, enumerate a million sums per side, sort one side, and binary search the complement."


Disclosure: I work on Linkjob.ai, an AI coding interview assistant. Notes are general study material.