Partition Array Into Two Arrays to Minimize Sum Difference - Problem

You are given an integer array nums of 2 * n integers. You need to partition nums into two arrays of length n to minimize the absolute difference of the sums of the arrays.

To partition nums, put each element of nums into one of the two arrays.

Return the minimum possible absolute difference.

Input & Output

Example 1 — Basic Case
$ Input: nums = [3,9,7,3]
Output: 2
💡 Note: Split into [3,9] and [7,3]. Sum difference is |12-10| = 2, which is minimal.
Example 2 — Perfect Split
$ Input: nums = [-36,36]
Output: 72
💡 Note: Only two elements, must split as [-36] and [36]. Difference is |-36-36| = 72.
Example 3 — Multiple Options
$ Input: nums = [2,-1,0,4,-2,-9]
Output: 0
💡 Note: Can split as [2,-1,-2] and [0,4,-9] both summing to -1. Difference is |-1-(-1)| = 0.

Constraints

  • 1 ≤ n ≤ 15
  • nums.length == 2 * n
  • -107 ≤ nums[i] ≤ 107

Visualization

Tap to expand
Partition Array to Minimize Sum Difference INPUT nums = [3, 9, 7, 3] 3 9 7 3 idx 0 idx 1 idx 2 idx 3 Split into 2 halves: [3, 9] Left Half [7, 3] Right Half n = 2 (need 2 elements each) Total sum = 22 Target = 11 each Goal: |sum1 - sum2| minimized ALGORITHM STEPS 1 Generate Subset Sums For each half, compute all possible subset sums 2 Group by Count Group sums by number of elements used (0,1,2,...n) 3 Sort Right Half Sums Sort for binary search 4 Binary Search Match Find best complement Left [3,9] k=0: {0} k=1: {3,9} k=2: {12} Right [7,3] k=0: {0} k=1: {3,7} k=2: {10} left[k] + right[n-k] = partition k=1: 9 + 3 = 12 (best!) Other: 3 + 7 = 10 FINAL RESULT Optimal Partition Found: Array 1 [9, 3] = 12 Array 2 [3, 7] = 10 |12 - 10| = 2 Minimum difference! OUTPUT 2 OK - Verified! Key Insight: Meet in the Middle reduces O(2^2n) to O(2^n). Split array into two halves, generate all subset sums for each half (2^n each), then use binary search to find the best combination where left picks k elements and right picks (n-k) elements, minimizing |sum1 - sum2| = |2*leftSum + rightSum - totalSum|. TutorialsPoint - Partition Array Into Two Arrays to Minimize Sum Difference | Meet in the Middle with Binary Search
Asked in
Google 45 Facebook 38 Microsoft 32 Amazon 28
23.4K Views
Medium Frequency
~45 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen