Domain 1EasyCORE

Find N Unique Integers Sum up to Zero

The problem requires generating an array of `n` unique integers that sum up to zero. The input is a single integer `n`, which specifies the number of elements in the output array. The output should be any valid array meeting the criteria.

Domain: Easy•Updated: 2026-08-31
#Algorithms#LeetCode#qwen2.5-coder:14b#Array

1304. Find N Unique Integers Sum up to Zero

Model: qwen2.5-coder:14b
Topics: Array
FAANG asked: 0
Acceptance rate: 76.7%


Problem Breakdown

The problem requires generating an array of n unique integers that sum up to zero. The input is a single integer n, which specifies the number of elements in the output array. The output should be any valid array meeting the criteria.

Inputs:

  • An integer n (1 <= n <= 1000)

Outputs:

  • An array of n unique integers that sum to zero

Implicit Constraints or Edge Cases:

  • If n is odd, include a zero in the array.
  • If n is even, the array should consist of pairs of positive and negative integers.

Intuition

A brute-force approach would involve generating all possible combinations of n unique integers and checking if their sum equals zero. However, this approach is computationally expensive with a time complexity of O(n!) due to the factorial number of permutations.

The key insight is that we can construct the array by pairing positive and negative integers around zero. For example, if n = 5, we can use [-2, -1, 0, 1, 2]. This approach ensures that the sum is always zero and leverages the properties of symmetry around zero.

Approach

  1. Initialize an empty list to store the result.
  2. If n is odd, add a zero to the list.
  3. For the remaining elements (which will be even), iterate from 1 to n//2.
    • Add both the positive and negative of the current number to the list.
  4. Return the constructed list.

This approach ensures that we have exactly n unique integers, and their sum is zero due to the symmetry around zero.

Complexity Analysis

  • Time Complexity: O(n) because we iterate through numbers from 1 to n//2, which takes linear time relative to n.
  • Space Complexity: O(n) for storing the result list of size n.

Solution

def sumZero(n):
    result = []
    
    # If n is odd, include zero in the array
    if n % 2 == 1:
        result.append(0)
    
    # Add pairs of positive and negative numbers
    for i in range(1, (n // 2) + 1):
        result.extend([i, -i])
    
    return result

Edge Cases Handled

  • Odd n: The code includes a zero when n is odd, ensuring the sum remains zero.
  • Even n: The code pairs positive and negative integers, maintaining the sum of zero without including zero.
  • Minimum n = 1: The code correctly returns [0] for the smallest possible input.