EasyNo. 1304

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

Topics
Array, Math
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

PythonSolution
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

Time
O(n)where n is the given integer
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
1295Find Numbers with Even Number of DigitsEasy
0048Rotate ImageMedium
0066Plus OneEasy
0189Rotate ArrayMedium
0204Count PrimesMedium
0335Self CrossingHard

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.

Free to download. Check it runs on your machine, then pick a plan.