Skip to main content
impol.dev

Editorial

Solution walkthrough

Review the explanation, then compare the reference implementation.

Video explanation

Solution

Intuition

Every pair x and -x contributes zero to the sum. Choosing distinct positive magnitudes keeps all pair members unique. If an odd number of entries is required, zero supplies the remaining element without changing the sum.

Approach

For each integer from one through floor(n / 2), append it and its negative. Append zero only when n is odd, then return the list. The construction has exactly n entries and total zero, and no two entries coincide. For n = 1, the loop is empty and the result is simply [0].

class Solution: def sumZero(self, n: int) -> List[int]: half = n // 2 res = [] for x in range(1, half + 1): res.append(x) res.append(-x) if n % 2 != 0: res.append(0) return res

Complexity analysis

The construction appends exactly n integers, so it takes O(n) time and produces O(n) output space with O(1) auxiliary state beyond the result.