We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find N Unique Integers Sum up to Zero

Number: 1426

Difficulty: Easy

Paid? No

Companies: Amazon, Microsoft


Problem Description

Given a positive integer n, generate any array of n unique integers such that their sum equals zero. There is always at least one valid solution.


Key Insights

  • For even values of n, you can use symmetric pairs of integers (x, -x).
  • For odd values of n, you can take the solution for n-1 (even) and add the extra integer 0.
  • This approach guarantees unique integers and a total sum of zero.
  • The solution is straightforward and leverages simple arithmetic properties.

Space and Time Complexity

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


Solution

The solution uses a simple iterative approach. We generate symmetric pairs of numbers for n/2 rounds and add 0 when n is odd. The main data structure used is an array (or list) that will store the unique integers. The trick is to realize that for each positive integer, its negative counterpart is generated, thereby ensuring the total sum is zero. If n is odd, appending 0 does not disturb the sum.


Code Solutions

# Function to generate n unique integers summing to zero
def sumZero(n):
    result = []  # List to store the result integers
    # Add pairs: i and -i for i from 1 to n//2
    for i in range(1, n // 2 + 1):
        result.append(i)  # Append positive integer
        result.append(-i) # Append its negative counterpart
    # If n is odd, append 0 to complete the list
    if n % 2 == 1:
        result.append(0)
    return result

# Example usage:
print(sumZero(5))  # Example output: [1, -1, 2, -2, 0]
← Back to All Questions