Find N Unique Integers Sum up to Zero
LeetCode 1426 | Difficulty: Easyβ
EasyProblem Descriptionβ
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`
Topics: Array, Math
Approachβ
Mathematicalβ
Look for mathematical patterns or formulas. Consider: modular arithmetic, GCD/LCM, prime factorization, combinatorics, or geometric properties.
When to use
Problems with clear mathematical structure, counting, number properties.
Solutionsβ
Solution 1: C# (Best: 123 ms)β
| Metric | Value |
|---|---|
| Runtime | 123 ms |
| Memory | 32.7 MB |
| Date | 2021-12-17 |
Solution
public class Solution {
public int[] SumZero(int n) {
int[] result = new int[n];
int sum = 0;
for(int i=0;i<n-1;i++)
{
result[i] = i+1;
sum += result[i];
}
result[n-1] = -sum;
return result;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Solution | $O(n)$ | $O(1) to O(n)$ |
Interview Tipsβ
Key Points
- Start by clarifying edge cases: empty input, single element, all duplicates.
- LeetCode provides 2 hint(s) for this problem β try solving without them first.
π‘ Hints
Hint 1: Return an array where the values are symmetric. (+x , -x).
Hint 2: If n is odd, append value 0 in your returned array.