Best solutions for Microsoft interview tasks. Unique Integers That Sum Up To 0

Description:

Given an integer n, return any array containing n unique integers such that they add up to 0.

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].
Input: n = 3
Output: [-1,0,1]
Input: n = 1
Output: [0]

Solution:

This task is very simple. We don’t need to play with a random number generator. We just need to make an array of different numbers. For example sequence 012345 contains different and unique numbers. So we just generate two the same sequences of numbers and make one of them negative. For example:

vector<int> solution(int n) {
vector<int> v;
v.reserve(n);
int until = n/2;
// if n is odd
if (n & 1) { v.push_back(0); }
for (int i = 1; i <= until; ++i) {
v.push_back(i); v.push_back(-i);
}
return v;
}
vector<int> solution2(int n) {
vector<int> v(n);
for (int i = 0; i < n; ++i) {
v[i] = i * 2 - n + 1;
}
return v;
}

Looking for an interesting project to join. https://www.linkedin.com/in/molchevsky/