Difficulty: Easy | Acceptance: 78.40% | Paid: No Topics: Array, Math
Given an integer n, return any array containing n unique integers such that they add up to 0.
- Examples
- Constraints
- Symmetric Pairs
- Arithmetic Progression
- Sum of First N-1
Examples
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].
Input: n = 3
Output: [-1,0,1]
Input: n = 1
Output: [0]
Constraints
1 <= n <= 1000
Symmetric Pairs
Intuition We can generate pairs of positive and negative integers (e.g., 1 and -1, 2 and -2). These pairs naturally sum to zero. If n is odd, we simply add 0 to the array.
Steps
- Initialize an empty list to store the result.
- Iterate from 1 to n // 2.
- In each iteration, add the current integer i and its negative -i to the list.
- If n is odd, append 0 to the list to handle the remaining element.
- Return the list.
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 != 0:
res.append(0)
return resComplexity
- Time: O(n)
- Space: O(1) (excluding the output array)
- Notes: This approach is very intuitive and efficient.
Arithmetic Progression
Intuition A sequence of consecutive integers centered around zero will always sum to zero. For example, for n=3, we can use -1, 0, 1. For n=4, we can use -3, -1, 1, 3 (step of 2) or simply -1, 0, 1, 2 offset by a constant. A simpler way is to generate numbers from -(n-1) to (n-1) with a step of 2.
Steps
- Calculate the starting value as -(n - 1).
- Loop n times.
- In each iteration, add the current value to the result and increment the value by 2.
- Return the result.
class Solution:
def sumZero(self, n: int) -> list[int]:
return [i - (n - 1) // 2 for i in range(n)]Complexity
- Time: O(n)
- Space: O(1) (excluding the output array)
- Notes: This approach generates a sorted array, which might be desirable in some contexts.
Sum of First N-1
Intuition We can generate the first n-1 unique integers (e.g., 1, 2, …, n-1). The sum of these is S. To make the total sum zero, the nth integer must be -S. This guarantees uniqueness because -S will be distinct from the positive integers 1 to n-1.
Steps
- Initialize an empty list.
- Iterate from 1 to n-1, adding each number to the list and keeping a running sum.
- Append the negative of the running sum to the list.
- Handle the edge case where n=1 by returning [0].
class Solution:
def sumZero(self, n: int) -> list[int]:
res = list(range(1, n))
res.append(-sum(res))
return resComplexity
- Time: O(n)
- Space: O(1) (excluding the output array)
- Notes: This approach is simple but results in a larger range of numbers compared to the symmetric approach.