Skip to content

Commit df94098

Browse files
authored
Create 1304-find-n-unique-integers-sum-up-to-zero.java
1 parent ddb9e88 commit df94098

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
/**
2+
* Problem: Generate an array of n unique integers such that their sum is 0.
3+
*
4+
* Approach 1:
5+
* - Start from 1 and alternate adding -num and +num into the array.
6+
* - If n is odd, include 0 in the array.
7+
* - This ensures symmetry and guarantees the sum is zero.
8+
*
9+
* Time Complexity: O(n)
10+
* Space Complexity: O(n)
11+
*/
12+
class Solution {
13+
public int[] sumZero(int n) {
14+
if (n == 1) return new int[n];
15+
16+
int[] arr = new int[n];
17+
int index = 0;
18+
if (n % 2 == 1) {
19+
index = 1; // Leave space for 0 if n is odd
20+
}
21+
22+
boolean flag = true;
23+
int num = 1;
24+
25+
while (index < n) {
26+
if (flag) {
27+
arr[index++] = -num;
28+
flag = false;
29+
} else {
30+
arr[index++] = num;
31+
flag = true;
32+
num++;
33+
}
34+
}
35+
36+
return arr;
37+
}
38+
}
39+
40+
/**
41+
* Approach 2 (Optimized and Cleaner):
42+
* - Pair numbers symmetrically: -1 & 1, -2 & 2, ..., until n/2 pairs.
43+
* - If n is odd, append 0 at the end.
44+
* - Cleaner logic without flags or while-loops.
45+
*
46+
* Time Complexity: O(n)
47+
* Space Complexity: O(n)
48+
*/
49+
class Solution {
50+
public int[] sumZero(int n) {
51+
int[] arr = new int[n];
52+
int pairs = n / 2;
53+
int index = 0;
54+
55+
for (int i = 1; i <= pairs; i++) {
56+
arr[index++] = -i;
57+
arr[index++] = i;
58+
}
59+
60+
if (n % 2 == 1) {
61+
arr[index] = 0;
62+
}
63+
64+
return arr;
65+
}
66+
}

0 commit comments

Comments
 (0)