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.
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
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;
} from bisect import bisect_left
def minimum_difference(nums):
n, total = len(nums) // 2, sum(nums)
def sums(half): # every subset sum, grouped by item count
by = [[] for _ in range(n + 1)]
for mask in range(1 << n):
by[bin(mask).count('1')].append(sum(x for i, x in enumerate(half) if mask >> i & 1))
return by
left, right = sums(nums[:n]), [sorted(r) for r in sums(nums[n:])]
best = float('inf')
for k in range(n + 1): # k items from the left, n - k from the right
rs = right[n - k]
for l in left[k]:
i = bisect_left(rs, (total - 2 * l) // 2) # r that brings l + r near total / 2
for j in (i - 1, i):
if 0 <= j < len(rs):
best = min(best, abs(total - 2 * (l + rs[j])))
return best // every subset sum of nums[start..start+n), grouped by how many items it uses
vector<vector<int>> sums(vector<int>& nums, int start, int n) {
vector<vector<int>> by(n + 1);
for (int mask = 0; mask < (1 << n); mask++) {
int s = 0;
for (int i = 0; i < n; i++) if (mask >> i & 1) s += nums[start + i];
by[__builtin_popcount(mask)].push_back(s);
}
return by;
}
int minimumDifference(vector<int>& nums) {
int n = nums.size() / 2, total = accumulate(nums.begin(), nums.end(), 0);
auto left = sums(nums, 0, n), right = sums(nums, n, n);
for (auto& r : right) sort(r.begin(), r.end());
int best = INT_MAX;
for (int k = 0; k <= n; k++) { // k items from the left half, n - k from the right
auto& rs = right[n - k];
for (int l : left[k]) {
int i = lower_bound(rs.begin(), rs.end(), (total - 2 * l) / 2) - rs.begin();
for (int j = max(0, i - 1); j <= min((int)rs.size() - 1, i); j++)
best = min(best, abs(total - 2 * (l + rs[j])));
}
}
return best;
} function minimumDifference(nums) {
const n = nums.length / 2, total = nums.reduce((a, b) => a + b, 0);
function sums(start) { // every subset sum, grouped by item count
const by = Array.from({ length: n + 1 }, () => []);
for (let mask = 0; mask < (1 << n); mask++) {
let s = 0, cnt = 0;
for (let i = 0; i < n; i++) if (mask >> i & 1) { s += nums[start + i]; cnt++; }
by[cnt].push(s);
}
return by;
}
const left = sums(0), right = sums(n).map(r => r.sort((a, b) => a - b));
let best = Infinity;
for (let k = 0; k <= n; k++) { // k items from the left half, n - k from the right
const rs = right[n - k];
for (const l of left[k]) {
const want = Math.trunc((total - 2 * l) / 2);
let lo = 0, hi = rs.length; // first r >= want
while (lo < hi) { const mid = (lo + hi) >> 1; if (rs[mid] < want) lo = mid + 1; else hi = mid; }
for (let j = Math.max(0, lo - 1); j <= Math.min(rs.length - 1, lo); j++)
best = Math.min(best, Math.abs(total - 2 * (l + rs[j])));
}
}
return best;
} The variations
-
1Split, enumerate both halves, binary search
List every subset sum of each half, grouped by how many items it uses. For a left sum
lwithkitems, binary search the sorted right sums withn − kitems for the one that bringsl + rclosest tototal / 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.
Lesson done
Back to Recursion & Backtracking →Mark it done once you can write the template from memory and you have solved the worked examples yourself.