Find N Unique Integers Sum up to Zero — LeetCode 1304 Python Solution

EasyArrayMath
Problem
#1304
Reading time
2 min

The problem

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

Example

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].

Python solution

Python
class Solution:
    def sumZero(self, n: int) -> List[int]:
        ans = []
        for i in range(n >> 1):
            ans.append(i + 1)
            ans.append(-(i + 1))
        if n & 1:
            ans.append(0)
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the given integer
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1304. Find N Unique Integers Sum up to Zero is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1304. Find N Unique Integers Sum up to Zero?
LeetCode 1304. Find N Unique Integers Sum up to Zero is rated Easy on LeetCode.
What is the time complexity of LeetCode 1304. Find N Unique Integers Sum up to Zero?
The Python solution on this page runs in O(n), where n is the given integer.
What is the space complexity of LeetCode 1304. Find N Unique Integers Sum up to Zero?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1304. Find N Unique Integers Sum up to Zero cover?
LeetCode 1304. Find N Unique Integers Sum up to Zero is tagged Array and Math on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview