Find N Unique Integers Sum up to Zero
EasyPrompt
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
Approaches
2 approaches with complexity analysis and trade-offs.
This approach involves building the array by adding n-1 unique integers and then calculating the final integer needed to make the sum of the array zero. For instance, we can add the integers 1, 2, ..., n-1.
Algorithm
- Create an integer array
resultof sizen. - Initialize a variable
currentSumto 0. - Iterate from
i = 0ton-2:- Set
result[i] = i + 1. - Add
i + 1tocurrentSum.
- Set
- Set the last element of the array,
result[n-1], to-currentSum. - Return the
resultarray.
Walkthrough
The core idea is to fill the first n-1 positions of the result array with simple, unique integers. A straightforward choice is to use the sequence 1, 2, 3, ..., n-1. While filling the array, we keep track of the sum of these numbers. After placing n-1 numbers, the sum will be S = 1 + 2 + ... + (n-1). To make the total sum of all n integers zero, the last integer must be -S. This guarantees the sum-to-zero property. We also need to ensure all n integers are unique. Since we added positive integers 1 through n-1, the final number -S will be negative (for n > 1) and thus distinct from the others. For the base case n=1, the loop is skipped, the sum is 0, and the result is [0], which is correct.
class Solution { public int[] sumZero(int n) { int[] result = new int[n]; int currentSum = 0; for (int i = 0; i < n - 1; i++) { result[i] = i + 1; currentSum += result[i]; } if (n > 0) { // To handle n=0 case if constraints allowed, though here n>=1 result[n - 1] = -currentSum; } return result; }}Complexity
Time
O(n) - We iterate once through the first `n-1` elements of the array to populate them. This is a single loop that runs `n-1` times, resulting in a linear time complexity.
Space
O(n) or O(1) - We need an array of size `n` to store and return the result. If the space for the output array is considered, the complexity is O(n). If not, the extra space used is O(1) for the sum variable.
Trade-offs
Pros
Conceptually simple and easy to implement.
Guaranteed to produce a correct and valid result for any
n >= 1.
Cons
The magnitude of the last number can be quite large. The sum of the first
kintegers isk*(k+1)/2. Forn=1000, the last number would be-(999*1000)/2 = -499500.Slightly less elegant compared to the symmetric approach.
A more elegant and efficient approach is to construct the array using symmetric pairs of integers (+x, -x). This naturally keeps the running sum at zero. If n is odd, a single zero is added to complete the array.
Algorithm
- Create an integer array
resultof sizen. - Iterate from
i = 1ton / 2(integer division).- Add
ito the result array. - Add
-ito the result array.
- Add
- If
nis an odd number, add0to the last remaining spot in the array. - Return the
resultarray.
Walkthrough
This method leverages a simple mathematical property: x + (-x) = 0. We can build the array by adding pairs of numbers (i, -i). We iterate from 1 up to n / 2. In each step, we add both i and -i to our result array. This ensures that for every positive number added, its additive inverse is also present, keeping the cumulative sum of the array at zero. All these numbers (1, -1, 2, -2, ...) are unique. If n is even, this process fills the entire array. If n is odd, this process fills n-1 spots, leaving one position empty. To complete the array without changing the sum (which is already 0), we simply add 0 to the last spot. The number 0 is unique as we only added non-zero integers previously.
class Solution { public int[] sumZero(int n) { int[] result = new int[n]; int index = 0; for (int i = 1; i <= n / 2; i++) { result[index++] = i; result[index++] = -i; } if (n % 2 == 1) { result[index] = 0; } return result; }}Complexity
Time
O(n) - The loop runs `n / 2` times. Inside the loop, we perform a constant number of operations (two array assignments). Therefore, the total time taken is proportional to `n`.
Space
O(n) or O(1) - Similar to the first approach, we require an array of size `n` for the output. The space complexity is O(n) if this is counted, and O(1) otherwise, as we only use a few variables for iteration.
Trade-offs
Pros
Very elegant and intuitive.
Produces integers with the smallest possible absolute values.
Extremely simple to implement and reason about.
Cons
There are no significant disadvantages to this approach; it is considered optimal for this problem.
Solutions
Solution
class Solution { public int [] sumZero ( int n ) { int [] ans = new int [ n ]; for ( int i = 1 , j = 0 ; i <= n / 2 ; ++ i ) { ans [ j ++] = i ; ans [ j ++] = - i ; } return ans ; } }class Solution { public: vector < int > sumZero ( int n ) { vector < int > ans ( n ); for ( int i = 1 , j = 0 ; i <= n / 2 ; ++ i ) { ans [ j ++ ] = i ; ans [ j ++ ] = - i ; } return ans ; } };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 ansVideo walkthrough
Newsletter
One sharp idea, every week
System design and interview prep — short enough to finish.
No spam. Unsubscribe anytime.
Practice
Same difficulty — related problems to reinforce the pattern.