Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created September 7, 2025 22:10
Show Gist options
  • Select an option

  • Save Ifihan/0f74a82f7e3649425d9f5e673249779a to your computer and use it in GitHub Desktop.

Select an option

Save Ifihan/0f74a82f7e3649425d9f5e673249779a to your computer and use it in GitHub Desktop.
Find N Unique Integers Sum up to Zero

Question

Approach

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.

Implementation

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

Complexities

  • Time: O(n)
  • Space: O(1)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment