Given an integer n, return any array containing n unique integers such that they add up to 0.
1 <= n <= 1000Use a flag to alternate between negative and positive numbers while building the array.
Algorithm:
Example Input: n = 5
Step-by-step execution:
Result: [0, -1, 1, -2, 2] (sum = 0)
class Solution {
public int[] sumZero(int n) {
if (n == 1) return new int[n];
int[] arr = new int[n];
int index = 0;
if (n % 2 == 1) {
index = 1; // Leave space for 0 if n is odd
}
boolean flag = true;
int num = 1;
while (index < n) {
if (flag) {
arr[index++] = -num;
flag = false;
} else {
arr[index++] = num;
flag = true;
num++;
}
}
return arr;
}
}
Create pairs of numbers that sum to zero: (-1, 1), (-2, 2), etc.
Algorithm:
Example Input: n = 5
Step-by-step execution:
Result: [-1, 1, -2, 2, 0] (sum = 0)
Example Input: n = 4
Step-by-step execution:
Result: [-1, 1, -2, 2] (sum = 0)
class Solution {
public int[] sumZero(int n) {
int[] arr = new int[n];
int pairs = n / 2;
int index = 0;
for (int i = 1; i <= pairs; i++) {
arr[index++] = -i;
arr[index++] = i;
}
if (n % 2 == 1) {
arr[index] = 0;
}
return arr;
}
}
| Approach | Time Complexity | Space Complexity | Readability | Edge Case Handling |
|---|---|---|---|---|
| Approach 1 | O(n) | O(n) | Medium | Good |
| Approach 2 | O(n) | O(n) | High | Excellent |
Key Insight: Both approaches generate the same mathematical pattern: pairs of numbers that cancel each other out, with 0 added for odd lengths.
Why This Works:
Alternative Mathematical Approaches:
[0, 1, 2, ..., n-1] transformed to sum to 0