Problem

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

Examples

Example 1

1
2
3
Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Example 2

1
2
Input: n = 3
Output: [-1,0,1]

Example 3

1
2
Input: n = 1
Output: [0]

Constraints

  • 1 <= n <= 1000

Solution

Method 1 – Symmetric Construction

Intuition

To get n unique integers that sum to zero, we can pair numbers symmetrically around zero (e.g., -1 and 1, -2 and 2, …). If n is odd, include 0 as well.

Approach

  1. Initialize an empty list.
  2. For i from 1 to n//2, add -i and i to the list.
  3. If n is odd, add 0 to the list.
  4. Return the list.

Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
public:
    vector<int> sumZero(int n) {
        vector<int> ans;
        for (int i = 1; i <= n/2; ++i) {
            ans.push_back(i);
            ans.push_back(-i);
        }
        if (n % 2 == 1) ans.push_back(0);
        return ans;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
func sumZero(n int) []int {
    ans := []int{}
    for i := 1; i <= n/2; i++ {
        ans = append(ans, i, -i)
    }
    if n%2 == 1 {
        ans = append(ans, 0)
    }
    return ans
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
    public int[] sumZero(int n) {
        int[] ans = new int[n];
        int idx = 0;
        for (int i = 1; i <= n/2; i++) {
            ans[idx++] = i;
            ans[idx++] = -i;
        }
        if (n % 2 == 1) ans[idx] = 0;
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
    fun sumZero(n: Int): IntArray {
        val ans = mutableListOf<Int>()
        for (i in 1..n/2) {
            ans.add(i)
            ans.add(-i)
        }
        if (n % 2 == 1) ans.add(0)
        return ans.toIntArray()
    }
}
1
2
3
4
5
6
7
8
class Solution:
    def sumZero(self, n: int) -> list[int]:
        ans = []
        for i in range(1, n//2+1):
            ans.extend([i, -i])
        if n % 2 == 1:
            ans.append(0)
        return ans
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
impl Solution {
    pub fn sum_zero(n: i32) -> Vec<i32> {
        let mut ans = Vec::new();
        for i in 1..=n/2 {
            ans.push(i);
            ans.push(-i);
        }
        if n % 2 == 1 {
            ans.push(0);
        }
        ans
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
    sumZero(n: number): number[] {
        const ans: number[] = [];
        for (let i = 1; i <= Math.floor(n/2); i++) {
            ans.push(i, -i);
        }
        if (n % 2 === 1) ans.push(0);
        return ans;
    }
}

Complexity

  • ⏰ Time complexity: O(n), we generate n/2 pairs and possibly one zero.
  • 🧺 Space complexity: O(n), for the output array.