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.
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.
bisect_right - bisect_left) rather than assuming unique sums.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.