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