Facebook Pixel

1304. Find N Unique Integers Sum up to Zero

Problem Description

Given an integer n, you need to create an array containing exactly n unique integers that sum to 0.

The problem asks you to construct an array with the following requirements:

  • The array must contain exactly n integers
  • All integers in the array must be unique (no duplicates)
  • The sum of all integers in the array must equal 0

For example:

  • If n = 5, a valid answer could be [-2, -1, 0, 1, 2] because it has 5 unique integers and they sum to 0
  • If n = 3, a valid answer could be [-1, 0, 1]
  • If n = 4, a valid answer could be [-2, -1, 1, 2]

The solution approach uses a simple strategy of adding pairs of positive and negative integers. For each pair (i, -i), the sum is 0. When n is odd, we need to add one more element, which is 0 itself to maintain the total sum as 0.

The code iterates n/2 times, adding pairs like (1, -1), (2, -2), etc. The expression n >> 1 performs integer division by 2, and n & 1 checks if n is odd. If n is odd, it appends 0 to complete the array with exactly n elements.

Quick Interview Experience
Help others by sharing your interview experience
Have you seen this problem before?

Intuition

The key insight is that we need numbers that cancel each other out to achieve a sum of 0. The most straightforward way to create numbers that sum to 0 is to use pairs of opposites: for every positive number, include its negative counterpart.

Think about it this way: if we include the number 1, we can also include -1, and their sum is 0. Similarly, 2 and -2 sum to 0. This pattern gives us a simple construction method: for every positive integer i, include both i and -i in our array.

This pairing strategy works perfectly when n is even. For example, if n = 4, we can use [1, -1, 2, -2]. Each pair sums to 0, so the total sum is 0, and we have exactly 4 unique integers.

But what happens when n is odd? We can't make complete pairs. If n = 5, we can only make 2 complete pairs, which gives us 4 numbers. We need one more number that doesn't disturb our sum of 0. The perfect candidate is 0 itself! Adding 0 to any sum doesn't change it, so our array remains balanced at a sum of 0.

This leads to our algorithm:

  • Generate n/2 pairs of positive and negative integers: (1, -1), (2, -2), (3, -3), ...
  • If n is odd, add 0 to complete the array

This approach guarantees uniqueness (all numbers are different), ensures exactly n elements, and maintains a sum of 0.

Learn more about Math patterns.

Solution Approach

The implementation follows a straightforward approach using a simple list to build our result:

  1. Initialize an empty list: We start with an empty list ans that will store our result.

  2. Generate pairs of opposites: We iterate n >> 1 times (which is equivalent to n // 2). In each iteration i:

    • Add the positive number i + 1 to the list
    • Add its negative counterpart -(i + 1) to the list

    The reason we use i + 1 instead of just i is because our loop starts from i = 0, and we want to generate pairs starting from (1, -1) rather than (0, 0).

  3. Handle odd case: After generating all pairs, we check if n is odd using the bitwise operation n & 1:

    • If n & 1 evaluates to 1 (true), then n is odd
    • In this case, we append 0 to the list to make the total count equal to n
  4. Return the result: The list now contains exactly n unique integers that sum to 0.

Example walkthrough:

  • For n = 5:

    • Loop runs 2 times (5 >> 1 = 2)
    • First iteration (i = 0): adds 1 and -1
    • Second iteration (i = 1): adds 2 and -2
    • Since 5 & 1 = 1 (odd), add 0
    • Result: [1, -1, 2, -2, 0]
  • For n = 4:

    • Loop runs 2 times (4 >> 1 = 2)
    • First iteration: adds 1 and -1
    • Second iteration: adds 2 and -2
    • Since 4 & 1 = 0 (even), no additional element needed
    • Result: [1, -1, 2, -2]

The time complexity is O(n) as we iterate approximately n/2 times and perform constant-time operations. The space complexity is O(n) for storing the result array.

Ready to land your dream job?

Unlock your dream job with a 5-minute evaluator for a personalized learning plan!

Start Evaluator

Example Walkthrough

Let's walk through the solution with n = 5 to see how the algorithm builds an array of 5 unique integers that sum to 0.

Step 1: Initialize

  • Start with an empty array: ans = []
  • Calculate how many pairs we need: n >> 1 = 5 >> 1 = 2 pairs

Step 2: Generate pairs

First iteration (i = 0):

  • Add positive number: i + 1 = 0 + 1 = 1
  • Add negative number: -(i + 1) = -1
  • Array becomes: [1, -1]
  • Running sum: 1 + (-1) = 0

Second iteration (i = 1):

  • Add positive number: i + 1 = 1 + 1 = 2
  • Add negative number: -(i + 1) = -2
  • Array becomes: [1, -1, 2, -2]
  • Running sum: 1 + (-1) + 2 + (-2) = 0

Step 3: Handle odd case

  • Check if n is odd: n & 1 = 5 & 1 = 1 (true, so n is odd)
  • We have 4 elements but need 5, so append 0
  • Array becomes: [1, -1, 2, -2, 0]

Step 4: Verify the result

  • Count: 5 elements ✓
  • All unique: {1, -1, 2, -2, 0} ✓
  • Sum: 1 + (-1) + 2 + (-2) + 0 = 0

The final array [1, -1, 2, -2, 0] satisfies all requirements: it contains exactly 5 unique integers that sum to 0.

Solution Implementation

1class Solution:
2    def sumZero(self, n: int) -> List[int]:
3        """
4        Generate an array of n unique integers that sum to zero.
5      
6        Args:
7            n: The number of integers to generate
8          
9        Returns:
10            A list of n unique integers with sum equal to 0
11        """
12        result = []
13      
14        # Add pairs of positive and negative integers
15        # n >> 1 is equivalent to n // 2 (integer division)
16        for i in range(n >> 1):
17            # Add positive integer (i+1)
18            result.append(i + 1)
19            # Add corresponding negative integer -(i+1)
20            result.append(-(i + 1))
21      
22        # If n is odd, add 0 to maintain zero sum
23        # n & 1 checks if n is odd (equivalent to n % 2 == 1)
24        if n & 1:
25            result.append(0)
26          
27        return result
28
1class Solution {
2    /**
3     * Returns an array of n unique integers that sum to 0.
4     * The approach uses pairs of positive and negative integers.
5     * 
6     * @param n the size of the array to generate
7     * @return an array of n unique integers with sum equal to 0
8     */
9    public int[] sumZero(int n) {
10        // Initialize result array with size n
11        int[] result = new int[n];
12      
13        // Fill the array with pairs of positive and negative integers
14        // We iterate from 1 to n/2 and place each number and its negative
15        int index = 0;
16        for (int i = 1; i <= n / 2; i++) {
17            // Add positive number
18            result[index++] = i;
19            // Add corresponding negative number
20            result[index++] = -i;
21        }
22      
23        // If n is odd, the last element remains 0 (default value)
24        // This ensures the sum is still 0
25      
26        return result;
27    }
28}
29
1class Solution {
2public:
3    vector<int> sumZero(int n) {
4        // Create a result vector of size n
5        vector<int> result(n);
6      
7        // Fill the array with pairs of positive and negative integers
8        // For n/2 pairs, add both i and -i to ensure sum is zero
9        int index = 0;
10        for (int i = 1; i <= n / 2; ++i) {
11            result[index++] = i;      // Add positive number
12            result[index++] = -i;     // Add corresponding negative number
13        }
14      
15        // If n is odd, the last element remains 0 (default initialized)
16        // This ensures the total sum is still zero
17      
18        return result;
19    }
20};
21
1/**
2 * Generates an array of n unique integers that sum to zero
3 * @param n - The number of integers to generate
4 * @returns An array of n integers that sum to zero
5 */
6function sumZero(n: number): number[] {
7    // Initialize result array with n zeros
8    const result: number[] = new Array(n).fill(0);
9  
10    // Fill the array with positive and negative pairs
11    // Stop at n/2 to ensure we don't exceed array bounds
12    let currentIndex: number = 0;
13    for (let i: number = 1; i <= Math.floor(n / 2); i++) {
14        // Add positive number
15        result[currentIndex++] = i;
16        // Add corresponding negative number
17        result[currentIndex++] = -i;
18    }
19  
20    // If n is odd, the middle element remains 0 (from initialization)
21    // This ensures the sum is always zero
22    return result;
23}
24

Time and Space Complexity

Time Complexity: O(n)

The algorithm iterates through a loop n >> 1 times (which is n/2 times). In each iteration, it performs constant time operations - appending two elements to the list. After the loop, there's a conditional check and potentially one more append operation, both taking constant time. Therefore, the total number of operations is proportional to n/2 * 2 = n, resulting in O(n) time complexity.

Space Complexity: O(n)

The algorithm creates a list ans that stores exactly n integers. When n is even, it stores n/2 positive integers and n/2 negative integers. When n is odd, it stores (n-1)/2 positive integers, (n-1)/2 negative integers, and one zero. In both cases, the total space used is proportional to n, giving us O(n) space complexity. Note that this is the space for the output array itself, which is required by the problem, and there are no additional data structures using significant auxiliary space.

Learn more about how to find time and space complexity quickly.

Common Pitfalls

1. Using Zero in Pairs for Even Numbers

A common mistake is including zero unnecessarily when n is even, which wastes a slot that could be used for another unique number.

Incorrect approach:

def sumZero(self, n: int) -> List[int]:
    result = [0]  # Always starting with 0
    for i in range(1, n // 2 + 1):
        if len(result) < n:
            result.append(i)
            result.append(-i)
    return result[:n]  # Truncating to size n

This approach fails for even n because it includes an unnecessary 0 and then has to truncate the list, potentially losing the balance of positive/negative pairs.

2. Starting Pairs from Zero

Another pitfall is forgetting to offset the loop variable when generating pairs, resulting in duplicate zeros.

Incorrect approach:

def sumZero(self, n: int) -> List[int]:
    result = []
    for i in range(n >> 1):
        result.append(i)    # Starting from 0
        result.append(-i)   # This adds 0 and -0 (which is 0)
    if n & 1:
        result.append(0)
    return result

When i = 0, this adds [0, 0] to the result, violating the uniqueness requirement.

3. Off-by-One Errors in Loop Range

Using incorrect loop bounds can result in arrays with wrong sizes.

Incorrect approach:

def sumZero(self, n: int) -> List[int]:
    result = []
    for i in range(n // 2 + 1):  # Wrong upper bound
        result.append(i + 1)
        result.append(-(i + 1))
    if n & 1:
        result.append(0)
    return result

This generates too many elements because the loop runs one extra iteration.

4. Not Handling Edge Cases

Failing to consider small values of n like 1 or 2.

Solution to avoid these pitfalls: The correct implementation should:

  • Only add 0 when n is odd
  • Start pairs from 1, not 0 (using i + 1)
  • Use exactly n // 2 iterations for pairs
  • Handle all values of n >= 1 correctly

Alternative correct approach to demonstrate flexibility:

def sumZero(self, n: int) -> List[int]:
    # Another valid approach using symmetric range
    half = n // 2
    result = list(range(-half, half + 1))
    if n % 2 == 0:
        result.remove(0)  # Remove 0 for even n
    return result

This generates a symmetric range around zero and removes the zero element when n is even, ensuring exactly n unique integers that sum to 0.

Discover Your Strengths and Weaknesses: Take Our 5-Minute Quiz to Tailor Your Study Plan:

Consider the classic dynamic programming of fibonacci numbers, what is the recurrence relation?


Recommended Readings

Want a Structured Path to Master System Design Too? Don’t Miss This!

Load More