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 <= 1000This approach involves using numbers in symmetric pairs to achieve the sum of zero. For example, if n is even, you can use pairs like (-1, 1), (-2, 2), etc. If n is odd, include zero to the list to keep the sum zero.
The function first allocates memory for the array and iterates to add pairs of integers, their negatives and zero for an odd n. It uses dynamic memory allocation to return the array.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) because it processes n elements. Space Complexity: O(n) because it returns an array of n elements.
This approach utilizes consecutive integers starting from 1-n and converting half to negative. The sequence is constructed such that all elements are positive in the first half and their negative counterparts in the second, ensuring zero sum.
The C solution sums numbers and alters the last number to correct the sum to zero. Numbers 1 to n-1 remain positive, with a compensating last element.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n). Space Complexity: O(n).
| Approach | Complexity |
|---|---|
| Use Symmetric Pairing | Time Complexity: O(n) because it processes n elements. Space Complexity: O(n) because it returns an array of n elements. |
| Consecutive Integers Strategy | Time Complexity: O(n). Space Complexity: O(n). |
Leetcode 1304: Find N Unique Integers Sum up to Zero • Algorithms Casts • 3,413 views views
Watch 9 more video solutions →Practice Find N Unique Integers Sum up to Zero with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor