Find N Unique Integers Sum up to Zero Problem
#1304
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1304.
Given an integer n, return any array containing n unique integers such that they add up to 0.
Example 1:
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].
Example 2:
Input: n = 3
Output: [-1,0,1]
Example 3:
Input: n = 1
Output: [0]
Constraints:
1 <= n <= 1000
Solution
Approach: Pairs That Cancel Out
Any x and -x add up to 0, so take the pairs 1, -1, 2, -2, ..., up to n / 2. All these numbers are different, and their sum is 0.
That gives an even count. When n is odd, one number is still missing: add 0, which keeps the sum at 0 and is different from every number in the pairs. For n = 1 the answer is just [0].
Any valid array is accepted, so the order does not matter.
Complexity: O(n) time, and O(1) extra space besides the answer.
class Solution:
def sumZero(self, n: int) -> List[int]:
ans = []
for i in range(1, n // 2 + 1):
ans += [i, -i] # each pair cancels out
if n % 2 == 1:
ans.append(0) # odd n: one number is left over, and 0 changes nothing
return ans