Recursion & Backtracking · Pattern 9 of 9

Meet in the middle: two half-sized searches

When 2^n is too many but 2^(n/2) is fine, split the items in half, list every subset sum of each half, sort one side and binary search it for the best partner of each sum on the other side.

1 variation · 1 problem

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • n is around 30 to 40: too big for 2^n, small enough for 2^(n/2)
  • Pick a subset whose sum is closest to a target
  • Split items into two groups with a fixed size each

The template

Meet in the Middle
int minimumDifference(int[] nums) {
    int n = nums.length / 2, total = 0;
    for (int x : nums) total += x;
    List<List<Integer>> left = sums(nums, 0, n), right = sums(nums, n, n);
    for (List<Integer> r : right) Collections.sort(r);
    int best = Integer.MAX_VALUE;
    for (int k = 0; k <= n; k++) {                 // k items from the left half, n - k from the right
        List<Integer> rs = right.get(n - k);
        for (int l : left.get(k)) {
            int want = (total - 2 * l) / 2;         // best r makes l + r close to total / 2
            int i = Collections.binarySearch(rs, want);
            if (i < 0) i = -i - 1;                  // first r >= want
            for (int j = Math.max(0, i - 1); j <= Math.min(rs.size() - 1, i); j++)
                best = Math.min(best, Math.abs(total - 2 * (l + rs.get(j))));
        }
    }
    return best;
}
// every subset sum of nums[start..start+n), grouped by how many items it uses
List<List<Integer>> sums(int[] nums, int start, int n) {
    List<List<Integer>> by = new ArrayList<>();
    for (int i = 0; i <= n; i++) by.add(new ArrayList<>());
    for (int mask = 0; mask < (1 << n); mask++) {
        int s = 0;
        for (int i = 0; i < n; i++) if ((mask >> i & 1) == 1) s += nums[start + i];
        by.get(Integer.bitCount(mask)).add(s);
    }
    return by;
}

The variations

  1. 1Split, enumerate both halves, binary search

    List every subset sum of each half, grouped by how many items it uses. For a left sum l with k items, binary search the sorted right sums with n − k items for the one that brings l + r closest to total / 2.

Mistakes to avoid

  • Ignoring the size rule: when each group must have exactly n items, a left subset with k items may only pair with right subsets of n − k items.
  • Checking only the first right sum at or above the target: the one just below it can be closer.
  • Trying this when plain pick / not-pick would do: for n up to about 20, the simpler search is fast enough.
Back to Recursion & Backtracking →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.