Tug of War

Pattern: Subsets

hard

Split the numbers into two teams of n/2 (one team one bigger when n is odd) so the sums are as close as possible. Choose which elements join the first team by backtracking, and once it is full compare 2 × its sum with the total.

The problem

Given n whole numbers, divide them into two groups whose sizes differ by at most one (sizes ⌊n / 2⌋ and ⌈n / 2⌉), so that the difference between the two sums is as small as possible. Return that smallest difference. For example, [3, 4, 5, -3, 100, 1, 89, 54, 23, 20] gives 0: {4, 100, 1, 23, 20} and {3, 5, -3, 89, 54} both sum to 148.

The link above is a GeeksforGeeks article, which prints the two groups. The function name tugOfWar and the "return the smallest difference" output are this guide's own.

Think first

  • If one group has sum s, what is the other group's sum?
  • How many ways are there to choose n / 2 elements?
  • When can a branch stop because it cannot fill the group?

Hints

    Brute force, and why it fails

    Try all 2ⁿ subsets and keep those of the right size: O(2ⁿ). Choosing exactly n / 2 elements explores C(n, n/2) groups, still exponential but smaller. A DP over (count, sum) works when the values are small.

    The key insight

    Only the first group needs choosing; the second is everything else. Its size is fixed, which prunes every branch that can no longer fill it.

    Dry run

    total4
    half2

    nums = [1, 1, 1, 1]. Total 4. The first team takes 2 elements.

    Step 1 of 4

    The plan

    best = infinity, half = n / 2
    function choose(i, taken, sum):
        if taken == half: best = min(best, |total - 2 sum|); return
        if n - i < half - taken: return
        choose(i + 1, taken + 1, sum + a[i])
        choose(i + 1, taken, sum)
    choose(0, 0, 0)
    return best
    

    Complexity

    Time
    O(C(n, n/2))
    Space
    O(n)

    One leaf per possible first group. The recursion is n deep.

    Edge cases

    • One number: one group is empty, so the answer is its absolute value.
    • Two numbers: their difference.
    • Negative values: the formula still holds.
    I've built my logic, show the code

    Java

    class Solution {
        private int best;
    
        public int tugOfWar(int[] nums) {
            int total = 0;
            for (int v : nums) total += v;
            best = Integer.MAX_VALUE;
            choose(nums, 0, 0, 0, total);
            return best;
        }
    
        private void choose(int[] nums, int i, int taken, int sum, int total) {
            int n = nums.length, half = n / 2;
            if (taken == half) {                            // one side is full: the rest is the other side
                best = Math.min(best, Math.abs(total - 2 * sum));
                return;
            }
            if (n - i < half - taken) return;               // not enough elements left to fill this side
            choose(nums, i + 1, taken + 1, sum + nums[i], total);   // nums[i] on this side
            choose(nums, i + 1, taken, sum, total);                 // or on the other side
        }
    }

    C++

    class Solution {
    public:
        int best;
    
        int tugOfWar(vector<int>& nums) {
            int total = 0;
            for (int v : nums) total += v;
            best = INT_MAX;
            choose(nums, 0, 0, 0, total);
            return best;
        }
    
        void choose(vector<int>& nums, int i, int taken, int sum, int total) {
            int n = static_cast<int>(nums.size()), half = n / 2;
            if (taken == half) {                            // one side is full: the rest is the other side
                best = min(best, abs(total - 2 * sum));
                return;
            }
            if (n - i < half - taken) return;               // not enough elements left to fill this side
            choose(nums, i + 1, taken + 1, sum + nums[i], total);   // nums[i] on this side
            choose(nums, i + 1, taken, sum, total);                 // or on the other side
        }
    };

    Python

    class Solution:
        def tugOfWar(self, nums: list[int]) -> int:
            n, total = len(nums), sum(nums)
            half = n // 2
            best = float("inf")
    
            def choose(i: int, taken: int, s: int) -> None:
                nonlocal best
                if taken == half:                   # one side is full: the rest is the other side
                    best = min(best, abs(total - 2 * s))
                    return
                if n - i < half - taken:
                    return                          # not enough elements left to fill this side
                choose(i + 1, taken + 1, s + nums[i])   # nums[i] on this side
                choose(i + 1, taken, s)                 # or on the other side
    
            choose(0, 0, 0)
            return best

    Common mistakes

    • Ignoring the size rule, which turns it into a different (easier) problem.
    • Comparing sums of the two groups by building both, instead of using the total.
    • Forgetting the absolute value.

    Similar problems