Find N Unique Integers Sum up to Zero

easy array two pointers math

Problem

Given an integer n, return any array containing n unique integers such that they add up to 0.

Inputn = 5
Output[-2, -1, 1, 2, 0]
Pairs (1, −1) and (2, −2) cancel out, and the leftover middle slot is 0. The sum is 0 and all five values are distinct.
Inputn = 4
Output[-2, -1, 1, 2]
An even n needs no middle 0; the two symmetric pairs already sum to 0.

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;
}
Time: O(n) Space: O(n)