algoadvance

Leetcode 1304. Find N Unique Integers Sum up to Zero

Problem Statement:

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

Clarifying Questions:

  1. What is the range of the input integer n?
    • There are no specific constraints given, so we will assume that n is a non-negative integer.
  2. Can n be zero?
    • If n is zero, the output should be an empty array.
  3. Is there a specific order in which the integers should appear in the output array?
    • No specific order is mentioned, so any order is acceptable as long as the sum is zero.

Strategy:

  1. If n is zero, return an empty array.
  2. Otherwise, create an array of length n such that the sum of the elements is zero.
  3. One simple strategy is to include pairs of integers (-i, i) for i from 1 to n/2. This ensures each pair sums to zero.
  4. If n is odd, include 0 in the array since including 0 does not change the sum.

Code:

#include <vector>

std::vector<int> sumZero(int n) {
    std::vector<int> result;
    
    // Add pairs (-i, i) to the result vector
    for(int i = 1; i <= n / 2; ++i) {
        result.push_back(-i);
        result.push_back(i);
    }
    
    // If n is odd, add 0 to the result vector
    if(n % 2 == 1) {
        result.push_back(0);
    }
    
    return result;
}

Explanation:

Time Complexity:

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI