Tensorum
LeetCode 2035 · Advanced / Mixed

Partition Array Into Two Arrays to Minimize Sum Difference

LeetCode 2035 · Hard · solution, intuition & step-by-step walkthrough

Meet in the middle: subset sums by size + binary search.

HardArrayTwo PointersBinary SearchDynamic ProgrammingBit Manipulation
821 msruntime · beats 8%
57 MBmemory · beats 96%
1approach
2accepted runs · last 25 Sept 2024

This is how I solved Partition Array Into Two Arrays to Minimize Sum Difference (LeetCode 2035), a hard problem from the Advanced / Mixed pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

With 2n numbers, brute force over all splits is far too slow, so meet in the middle. Enumerate every subset of each half, grouped by how many elements it takes. Taking k from the left half means taking n − k from the right; for each left sum, binary-search the right sums for the value that makes the two sides closest to equal.

Approach

  1. 1

    Enumerate all masks of each half, storing sums by subset size.

  2. 2

    Start with taking all of one half.

  3. 3

    For each size k and left sum a, the ideal right sum is (total − 2a) / 2.

  4. 4

    Sort the right sums of size n − k and binary-search around that target.

  5. 5

    Keep the smallest |total − 2·(a + b)|.

How I solved it

Meet in the middlePythonO(2ⁿ·n) time
class Solution:
    def lowerBound(self, arr, val):
        low, high = 0, len(arr)
        while low < high:
            mid = (low + high) // 2
            if arr[mid] < val:
                low = mid + 1
            else:
                high = mid
        return low

    def minimumDifference(self, nums):
        total = sum(nums)
        N = len(nums)
        n = N // 2
        left = [[] for _ in range(n + 1)]
        right = [[] for _ in range(n + 1)]
        for mask in range(1 << n):
            sz = l = r = 0
            for i in range(n):
                if mask & (1 << i):
                    l += nums[i]
                    r += nums[i + n]
                    sz += 1
            left[sz].append(l)
            right[sz].append(r)
        res = min(abs(total - 2 * left[n][0]), abs(total - 2 * right[n][0]))
        for sz in range(1, n):
            right[n - sz].sort()
            for a in left[sz]:
                b = (total - 2 * a) / 2
                rsz = n - sz
                itr = self.lowerBound(right[rsz], b)
                if itr < len(right[rsz]):
                    res = min(res, abs(total - 2 * (a + right[rsz][itr])))
                if itr > 0:
                    res = min(res, abs(total - 2 * (a + right[rsz][itr - 1])))
        return res
Loading the step-through…

Partition Array Into Two Arrays to Minimize Sum Difference — FAQ

What is the intuition behind Partition Array Into Two Arrays to Minimize Sum Difference?

With 2n numbers, brute force over all splits is far too slow, so meet in the middle. Enumerate every subset of each half, grouped by how many elements it takes. Taking k from the left half means taking n − k from the right; for each left sum, binary-search the right sums for the value that makes the two sides closest to equal.

How do you solve Partition Array Into Two Arrays to Minimize Sum Difference (LeetCode 2035)?

1. Enumerate all masks of each half, storing sums by subset size. 2. Start with taking all of one half. 3. For each size k and left sum a, the ideal right sum is (total − 2a) / 2. 4. Sort the right sums of size n − k and binary-search around that target. 5. Keep the smallest |total − 2·(a + b)|.

What is the time and space complexity of Partition Array Into Two Arrays to Minimize Sum Difference?

Time: O(2ⁿ · n). Space: O(2ⁿ). (Accepted approach: Meet in the middle.)

What are common mistakes in Partition Array Into Two Arrays to Minimize Sum Difference?

Sizes must add to n — that's why sums are grouped by count.