Problem Statement in English

You’re given an integer n. Return any array containing n unique integers such that they add up to 0.


Approach

If we have a positive integer x, we should also include its negative counterpart -x to ensure the sum remains zero.

Further, if n is odd, we can include 0 in the array since it doesn’t affect the sum.


Solution in Python


class Solution:
    def sumZero(self, n: int) -> List[int]:
        res = []

        l = n // 2

        for i in range(1, l + 1):
            res.append(i)
            res.append(-i)

        if n % 2:
            res.append(0)

        return res

Complexity

  • Time: $O(n)$
    We are iterating through numbers from 1 to n/2, which takes linear time.

  • Space: $O(n)$
    We are storing the result in a list of size n.


And we are done.