Facebook Pixel

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

1def unique_sum(n: int) -> list[int]:
2    res = []
3    for i in range(n):
4        res.append(i * 2 - n + 1)
5    return res
6
7if __name__ == "__main__":
8    n = int(input())
9    res = unique_sum(n)
10    print(" ".join(map(str, res)))
11
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
1using System;
2using System.Collections.Generic;
3
4class Solution
5{
6    public static List<int> UniqueSum(int n) {
7        var res = new List<int>();
8        for (int i = 0; i < n; i++) {
9            res.Add(i * 2 - n + 1);
10        }
11        return res;
12    }
13
14    public static void Main()
15    {
16        int n = int.Parse(Console.ReadLine());
17        List<int> res = UniqueSum(n);
18        Console.WriteLine(string.Join(' ', res));
19    }
20}
21
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
1function uniqueSum(n: number): number[] {
2    const v: number[] = [];
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?: string) => 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
1#include <algorithm>
2#include <iostream>
3#include <iterator>
4#include <limits>
5#include <vector>
6
7std::vector<int> unique_sum(int n) {
8    std::vector<int> res;
9    for (int i = 0; i < n; i++) {
10        res.push_back(i * 2 - n + 1);
11    }
12    return res;
13}
14
15void ignore_line() {
16    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
17}
18
19template<typename T>
20void put_words(const std::vector<T>& v) {
21    if (!v.empty()) {
22        std::copy(v.begin(), std::prev(v.end()), std::ostream_iterator<T>{std::cout, " "});
23        std::cout << v.back();
24    }
25    std::cout << '\n';
26}
27
28int main() {
29    int n;
30    std::cin >> n;
31    ignore_line();
32    std::vector<int> res = unique_sum(n);
33    put_words(res);
34}
35
1use std::error;
2use std::fmt::Display;
3use std::io;
4
5pub fn unique_sum(n: i32) -> Vec<i32> {
6    let mut res = Vec::new();
7    for i in 0..n {
8        res.push(i * 2 - n + 1);
9    }
10    res
11}
12
13fn print_words<T: Display>(v: &Vec<T>) {
14    let mut iter = v.iter();
15    if let Some(val) = iter.next() {
16        print!("{}", val);
17        for val in iter {
18            print!(" {}", val);
19        }
20    }
21    println!();
22}
23
24fn main() -> Result<(), Box<dyn error::Error>> {
25    let mut line = String::new();
26    io::stdin().read_line(&mut line)?;
27    let n = line.trim_end().parse()?;
28    let res = unique_sum(n);
29    print_words(&res);
30    Ok(())
31}
32
1package main
2
3import (
4    "bufio"
5    "fmt"
6    "os"
7    "strconv"
8    "strings"
9)
10
11func uniqueSum(n int) []int {
12    res := make([]int, 0)
13    for i := 0; i < n; i++ {
14        res = append(res, i*2-n+1)
15    }
16    return res
17}
18
19func arrayItoa(arr []int) []string {
20    res := []string{}
21    for _, v := range arr {
22        res = append(res, strconv.Itoa(v))
23    }
24    return res
25}
26
27func main() {
28    scanner := bufio.NewScanner(os.Stdin)
29    scanner.Scan()
30    n, _ := strconv.Atoi(scanner.Text())
31    res := uniqueSum(n)
32    fmt.Println(strings.Join(arrayItoa(res), " "))
33}
34
1def unique_sum(n)
2    res = []
3    (0...n).each do |i|
4        res.push(i * 2 - n + 1)
5    end
6    res
7end
8
9if __FILE__ == $0
10  n = Integer(gets, 10)
11  res = unique_sum(n)
12  puts(res.join(' '))
13end
14
1#lang racket
2
3(define (unique-sum n)
4  (for/list ([i (in-range n)])
5    (+ (* i 2) (- n) 1)))
6
7(define n (string->number (read-line)))
8(define res (unique-sum n))
9(displayln (string-join (map number->string res)))
10
1uniqueSum :: Int -> [Int]
2uniqueSum n = [i * 2 - n + 1 | i <- [0..n-1]]
3
4main :: IO ()
5main = do
6  n <- readLn
7  let res = uniqueSum n
8  putStrLn $ unwords $ map show res
9
Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro