DEV Community


LeetCode 1304. Find N Unique Integers Sum up to Zero (javascript solution) | Microsoft Question

cod3pineapple profile image codingpineapple ・1 min read


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


Time Complexity : O(n)
Space Complexity: O(n)

var sumZero = function(n) {
    // Initalize output array with all 0s
    let output = Array(n).fill(0);
    // Increase i by 2 to add each number and it's negative value to output on each loop so that the total sum of the entire array will always be 0
    for (let i = 0; i < n - 1; i += 2) {
        // Use i + 1 because we already initialized 0 to be in the array
        // If n is an odd number the last number in output will be zero (because we increase i by 2, we will aways stop at an even number,leaving one space at the end that will stay 0) and every other number in output will be paired with its negative value to keep the sum of output to be 0
        // If n is even then all numbers in output will cancel each other out and the sum will be 0
        output[i] = i + 1;
        output[i + 1] = -(i + 1);
    return output;
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

Editor guide