Meet in the Middle - Example

4Sum II problem.

Problem: Find if any subset of 4040 numbers sums to target.

1.1. Split into two halves of 2020.

2.2. Generate all 2202^{20} sums for each half.

3.3. Sort second half. For each sum ss in first half, binary search for targetstarget - s.

for s in firstHalfSums:
    if binarySearch(secondHalfSums, target - s):
        return true

Time: O(2n/2n)O(2^{n/2} \cdot n) instead of O(2n)O(2^n). For n=40n=40: 10710^7 vs 101210^{12}.