Find N Unique Integers Sum up to Zero
Problem
Given an integer n, return any array containing n unique integers such that they add up to 0.
n = 5[-2, -1, 1, 2, 0]n = 4[-2, -1, 1, 2]def sum_zero(n):
res = [0] * n
left, right = 0, n - 1
val = 1
while left < right:
res[left] = val
res[right] = -val
left += 1
right -= 1
val += 1
return res
function sumZero(n) {
const res = new Array(n).fill(0);
let left = 0, right = n - 1, val = 1;
while (left < right) {
res[left] = val;
res[right] = -val;
left++;
right--;
val++;
}
return res;
}
int[] sumZero(int n) {
int[] res = new int[n];
int left = 0, right = n - 1, val = 1;
while (left < right) {
res[left] = val;
res[right] = -val;
left++;
right--;
val++;
}
return res;
}
vector<int> sumZero(int n) {
vector<int> res(n, 0);
int left = 0, right = n - 1, val = 1;
while (left < right) {
res[left] = val;
res[right] = -val;
left++;
right--;
val++;
}
return res;
}
Explanation
The trick is that any number and its negative cancel out: k + (−k) = 0. So if we fill the array with symmetric pairs like (1, −1), (2, −2), (3, −3), the running total stays exactly 0, and every value is distinct.
We use a two-pointer sweep from both ends. left starts at index 0, right at index n − 1, and a counter val starts at 1. On each iteration we write val at left and −val at right, then move the pointers inward and bump val.
The loop runs while left < right. When n is even the pointers cross cleanly, placing exactly n / 2 pairs. When n is odd the pointers meet at one untouched middle cell that keeps its initial value 0 — which is itself unique and contributes nothing to the sum.
Because every +val is matched by a −val and the optional middle is 0, the final array always sums to 0 while holding n distinct integers.
Example: n = 5 fills index 0 with 1 and index 4 with −1, then index 1 with 2 and index 3 with −2, leaving index 2 as 0, giving [1, 2, 0, −2, −1] (any permutation is accepted).