Microsoft Online Assessment (OA) - Unique Integers That Sum Up To 0

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

Example 1:

Input:5

Output: [-4,-2,0,2,4]

Example 2:

Input:3

Output: [-2, 0, 2]

Example 1:

Input:1

Output: [0]

Try it yourself

Implementation

1from typing import List
2
3def unique_sum(n: int) -> List[int]:
4    res = []
5    for i in range(n):
6        res.append(i * 2 - n + 1)
7    return res
8
9if __name__ == '__main__':
10    n = int(input())
11    res = unique_sum(n)
12    print(' '.join(map(str, res)))
13
1import java.util.ArrayList;
2import java.util.Arrays;
3import java.util.List;
4import java.util.Scanner;
5import java.util.stream.Collectors;
6
7class Solution {
8    public static List<Integer> uniqueSum(int n) {
9        ArrayList<Integer> res = new ArrayList<>();
10        for (int i = 0; i < n; i++) {
11            res.add(i * 2 - n + 1);
12        }
13        return res;
14    }
15
16    public static void main(String[] args) {
17        Scanner scanner = new Scanner(System.in);
18        int n = Integer.parseInt(scanner.nextLine());
19        scanner.close();
20        List<Integer> res = uniqueSum(n);
21        System.out.println(res.stream().map(String::valueOf).collect(Collectors.joining(" ")));
22    }
23}
24
1function uniqueSum(n) {
2    const v = [];
3    for (let i = 0; i < n; i++) {
4        v.push(i * 2 - n + 1);
5    }
6    return v;
7}
8
9function* main() {
10    const n = parseInt(yield);
11    const res = uniqueSum(n);
12    console.log(res.join(' '));
13}
14
15class EOFError extends Error {}
16{
17    const gen = main();
18    const next = (line) => gen.next(line).done && process.exit();
19    let buf = '';
20    next();
21    process.stdin.setEncoding('utf8');
22    process.stdin.on('data', (data) => {
23        const lines = (buf + data).split('\n');
24        buf = lines.pop();
25        lines.forEach(next);
26    });
27    process.stdin.on('end', () => {
28        buf && next(buf);
29        gen.throw(new EOFError());
30    });
31}
32

Still not clear?Β SubmitΒ the part you don't understand to our editors.