Problem Statement
Pattern:
Solution
// simple approach
public int[] sumZero1(int n) {
int[] res = new int[n];
for (int i = 0 ; i < n-1 ; i++)
res[i++] = i+1;
// add last element -> -ve sum of elements b4 n
res[--n] = -n * (n+1) / 2;
return res;
}
// robust approach (n >= 10^5)
public int[] sumZero(int n) {
int[] res = new int[n];
for (int i = 0; i < n; i++)
res[i] = 2*i - n +1;
return res;
}
Notes
- First Appraoch is simple and straight fwd
- Fill array with numbers upto n-1
- last element is the negative sum of all the numbers
- Second approach is robust with large range of n
- [Java/C++/Python] Find the Rule - LeetCode Discuss
- Basically it will give you a patttern like this.
n = 3, [-2, 0, 2]
n = 4, [-3, -1, 1, 3]
n = 5, [-4, -2, 0, 2, 4]