To construct an array of n unique integers that sum to zero, I use a simple symmetric pairing method. If n is even, I can generate pairs like (1, -1), (2, -2), …, giving exactly n elements whose sum is zero. If n is odd, I do the same but also include a 0 to balance the count, since adding zero doesn’t affect the sum.
class Solution:
def sumZero(self, n: int) -> List[int]:
res = []
for i in range(1, n // 2 + 1):
res.append(i)
res.append(-i)
if n % 2 == 1:
res.append(0)
return res- Time: O(n)
- Space: O(1)