Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Break down a hard problem into reliable checkpoints, edge-case handling, and complexity trade-offs.
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.
Example 1:
Input: nums = [3,9,7,3] Output: 2 Explanation: One optimal partition is: [3,9] and [7,3]. The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.
Example 2:
Input: nums = [-36,36] Output: 72 Explanation: One optimal partition is: [-36] and [36]. The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.
Example 3:
Input: nums = [2,-1,0,4,-2,-9] Output: 0 Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2]. The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.
Constraints:
1 <= n <= 15nums.length == 2 * n-107 <= nums[i] <= 107Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers · Binary Search · Dynamic Programming · Bit Manipulation · Segment Tree
[3,9,7,3]
[-36,36]
[2,-1,0,4,-2,-9]
partition-equal-subset-sum)split-array-with-same-average)tallest-billboard)last-stone-weight-ii)fair-distribution-of-cookies)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2035: Partition Array Into Two Arrays to Minimize Sum Difference
class Solution {
public int minimumDifference(int[] nums) {
int n = nums.length >> 1;
Map<Integer, Set<Integer>> f = new HashMap<>();
Map<Integer, Set<Integer>> g = new HashMap<>();
for (int i = 0; i < (1 << n); ++i) {
int s = 0, cnt = 0;
int s1 = 0, cnt1 = 0;
for (int j = 0; j < n; ++j) {
if ((i & (1 << j)) != 0) {
s += nums[j];
++cnt;
s1 += nums[n + j];
++cnt1;
} else {
s -= nums[j];
s1 -= nums[n + j];
}
}
f.computeIfAbsent(cnt, k -> new HashSet<>()).add(s);
g.computeIfAbsent(cnt1, k -> new HashSet<>()).add(s1);
}
int ans = Integer.MAX_VALUE;
for (int i = 0; i <= n; ++i) {
List<Integer> fi = new ArrayList<>(f.get(i));
List<Integer> gi = new ArrayList<>(g.get(n - i));
Collections.sort(fi);
Collections.sort(gi);
for (int a : fi) {
int left = 0, right = gi.size() - 1;
int b = -a;
while (left < right) {
int mid = (left + right) >> 1;
if (gi.get(mid) >= b) {
right = mid;
} else {
left = mid + 1;
}
}
ans = Math.min(ans, Math.abs(a + gi.get(left)));
if (left > 0) {
ans = Math.min(ans, Math.abs(a + gi.get(left - 1)));
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #2035: Partition Array Into Two Arrays to Minimize Sum Difference
func minimumDifference(nums []int) int {
n := len(nums) >> 1
f := make([][]int, n+1)
g := make([][]int, n+1)
for i := 0; i < (1 << n); i++ {
s, cnt := 0, 0
s1, cnt1 := 0, 0
for j := 0; j < n; j++ {
if (i & (1 << j)) != 0 {
s += nums[j]
cnt++
s1 += nums[n+j]
cnt1++
} else {
s -= nums[j]
s1 -= nums[n+j]
}
}
f[cnt] = append(f[cnt], s)
g[cnt1] = append(g[cnt1], s1)
}
for i := 0; i <= n; i++ {
sort.Ints(f[i])
sort.Ints(g[i])
}
ans := 1 << 30
for i := 0; i <= n; i++ {
for _, a := range f[i] {
left, right := 0, len(g[n-i])-1
b := -a
for left < right {
mid := (left + right) >> 1
if g[n-i][mid] >= b {
right = mid
} else {
left = mid + 1
}
}
ans = min(ans, abs(a+g[n-i][left]))
if left > 0 {
ans = min(ans, abs(a+g[n-i][left-1]))
}
}
}
return ans
}
func abs(x int) int {
if x > 0 {
return x
}
return -x
}
# Accepted solution for LeetCode #2035: Partition Array Into Two Arrays to Minimize Sum Difference
class Solution:
def minimumDifference(self, nums: List[int]) -> int:
n = len(nums) >> 1
f = defaultdict(set)
g = defaultdict(set)
for i in range(1 << n):
s = cnt = 0
s1 = cnt1 = 0
for j in range(n):
if (i & (1 << j)) != 0:
s += nums[j]
cnt += 1
s1 += nums[n + j]
cnt1 += 1
else:
s -= nums[j]
s1 -= nums[n + j]
f[cnt].add(s)
g[cnt1].add(s1)
ans = inf
for i in range(n + 1):
fi, gi = sorted(list(f[i])), sorted(list(g[n - i]))
# min(abs(f[i] + g[n - i]))
for a in fi:
left, right = 0, len(gi) - 1
b = -a
while left < right:
mid = (left + right) >> 1
if gi[mid] >= b:
right = mid
else:
left = mid + 1
ans = min(ans, abs(a + gi[left]))
if left > 0:
ans = min(ans, abs(a + gi[left - 1]))
return ans
// Accepted solution for LeetCode #2035: Partition Array Into Two Arrays to Minimize Sum Difference
/**
* [2035] Partition Array Into Two Arrays to Minimize Sum Difference
*
* 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.
*
* Example 1:
* <img alt="example-1" src="https://assets.leetcode.com/uploads/2021/10/02/ex1.png" style="width: 240px; height: 106px;" />
* Input: nums = [3,9,7,3]
* Output: 2
* Explanation: One optimal partition is: [3,9] and [7,3].
* The absolute difference between the sums of the arrays is abs((3 + 9) - (7 + 3)) = 2.
*
* Example 2:
*
* Input: nums = [-36,36]
* Output: 72
* Explanation: One optimal partition is: [-36] and [36].
* The absolute difference between the sums of the arrays is abs((-36) - (36)) = 72.
*
* Example 3:
* <img alt="example-3" src="https://assets.leetcode.com/uploads/2021/10/02/ex3.png" style="width: 316px; height: 106px;" />
* Input: nums = [2,-1,0,4,-2,-9]
* Output: 0
* Explanation: One optimal partition is: [2,4,-9] and [-1,0,-2].
* The absolute difference between the sums of the arrays is abs((2 + 4 + -9) - (-1 + 0 + -2)) = 0.
*
*
* Constraints:
*
* 1 <= n <= 15
* nums.length == 2 * n
* -10^7 <= nums[i] <= 10^7
*
*/
pub struct Solution {}
// problem: https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/
// discuss: https://leetcode.com/problems/partition-array-into-two-arrays-to-minimize-sum-difference/discuss/?currentPage=1&orderBy=most_votes&query=
// submission codes start here
impl Solution {
pub fn minimum_difference(nums: Vec<i32>) -> i32 {
0
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
#[ignore]
fn test_2035_example_1() {
let nums = vec![3, 9, 7, 3];
let result = 2;
assert_eq!(Solution::minimum_difference(nums), result);
}
#[test]
#[ignore]
fn test_2035_example_2() {
let nums = vec![-36, 36];
let result = 72;
assert_eq!(Solution::minimum_difference(nums), result);
}
#[test]
#[ignore]
fn test_2035_example_3() {
let nums = vec![2, -1, 0, 4, -2, -9];
let result = 0;
assert_eq!(Solution::minimum_difference(nums), result);
}
}
// Accepted solution for LeetCode #2035: Partition Array Into Two Arrays to Minimize Sum Difference
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #2035: Partition Array Into Two Arrays to Minimize Sum Difference
// class Solution {
// public int minimumDifference(int[] nums) {
// int n = nums.length >> 1;
// Map<Integer, Set<Integer>> f = new HashMap<>();
// Map<Integer, Set<Integer>> g = new HashMap<>();
// for (int i = 0; i < (1 << n); ++i) {
// int s = 0, cnt = 0;
// int s1 = 0, cnt1 = 0;
// for (int j = 0; j < n; ++j) {
// if ((i & (1 << j)) != 0) {
// s += nums[j];
// ++cnt;
// s1 += nums[n + j];
// ++cnt1;
// } else {
// s -= nums[j];
// s1 -= nums[n + j];
// }
// }
// f.computeIfAbsent(cnt, k -> new HashSet<>()).add(s);
// g.computeIfAbsent(cnt1, k -> new HashSet<>()).add(s1);
// }
// int ans = Integer.MAX_VALUE;
// for (int i = 0; i <= n; ++i) {
// List<Integer> fi = new ArrayList<>(f.get(i));
// List<Integer> gi = new ArrayList<>(g.get(n - i));
// Collections.sort(fi);
// Collections.sort(gi);
// for (int a : fi) {
// int left = 0, right = gi.size() - 1;
// int b = -a;
// while (left < right) {
// int mid = (left + right) >> 1;
// if (gi.get(mid) >= b) {
// right = mid;
// } else {
// left = mid + 1;
// }
// }
// ans = Math.min(ans, Math.abs(a + gi.get(left)));
// if (left > 0) {
// ans = Math.min(ans, Math.abs(a + gi.get(left - 1)));
// }
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: An incomplete state merges distinct subproblems and caches incorrect answers.
Usually fails on: Correctness breaks on cases that differ only in hidden state.
Fix: Define state so each unique subproblem maps to one DP cell.