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: Split [3,9,7,3] into Two Equal Groups3973Need to split into two groups of 2 elements eachGroup 1: [3, 9]Sum = 12Group 2: [7, 3]Sum = 10Difference = |12 - 10| = 2Minimum Possible Difference: 2
Understanding the Visualization
1
Input Array
Array of 2n elements that needs equal partitioning
2
Find Optimal Split
Try different ways to partition into two equal groups
3
Minimum Difference
Return smallest possible |sum1 - sum2|
Key Takeaway
🎯 Key Insight: Use meet-in-the-middle to reduce exponential search space from O(2^(2n)) to O(3^n)
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