leetcode

Find N Unique Integers Sum up to Zero - Link

Question Description

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


Constraints


Approaches

Approach 1: Flag-Based Alternating Approach

Use a flag to alternate between negative and positive numbers while building the array.

Algorithm:

  1. Handle edge case: if n == 1, return empty array (no unique integers sum to 0)
  2. Create array of size n
  3. If n is odd, start from index 1 (reserve index 0 for 0)
  4. Use a flag to alternate between negative and positive numbers
  5. Start with num = 1 and increment after placing positive numbers
  6. Place 0 at the beginning if n is odd

Dry Run (Approach 1)

Example Input: n = 5

Step-by-step execution:

Result: [0, -1, 1, -2, 2] (sum = 0)


Solution (Approach 1)

class Solution {
    public int[] sumZero(int n) {
        if (n == 1) return new int[n];

        int[] arr = new int[n];
        int index = 0;
        if (n % 2 == 1) {
            index = 1; // Leave space for 0 if n is odd
        }

        boolean flag = true;
        int num = 1;

        while (index < n) {
            if (flag) {
                arr[index++] = -num;
                flag = false;
            } else {
                arr[index++] = num;
                flag = true;
                num++;
            }
        }

        return arr;
    }
}

Time and Space Complexity (Approach 1)


Approach 2: Pair-Based Approach (Cleaner)

Create pairs of numbers that sum to zero: (-1, 1), (-2, 2), etc.

Algorithm:

  1. Calculate number of pairs: pairs = n / 2
  2. Create array of size n
  3. Use a loop to place pairs: (-i, i) for i from 1 to pairs
  4. If n is odd, place 0 at the end
  5. This ensures sum is always 0

Dry Run (Approach 2)

Example Input: n = 5

Step-by-step execution:

Result: [-1, 1, -2, 2, 0] (sum = 0)

Example Input: n = 4

Step-by-step execution:

Result: [-1, 1, -2, 2] (sum = 0)


Solution (Approach 2)

class Solution {
    public int[] sumZero(int n) {
        int[] arr = new int[n];
        int pairs = n / 2;
        int index = 0;

        for (int i = 1; i <= pairs; i++) {
            arr[index++] = -i;
            arr[index++] = i;
        }

        if (n % 2 == 1) {
            arr[index] = 0;
        }

        return arr;
    }
}

Time and Space Complexity (Approach 2)


Comparison of Approaches

Approach Time Complexity Space Complexity Readability Edge Case Handling
Approach 1 O(n) O(n) Medium Good
Approach 2 O(n) O(n) High Excellent

Key Insight: Both approaches generate the same mathematical pattern: pairs of numbers that cancel each other out, with 0 added for odd lengths.

Why This Works:

Alternative Mathematical Approaches:

  1. Arithmetic Sequence: [0, 1, 2, ..., n-1] transformed to sum to 0
  2. Random Selection: Any n-1 numbers and their negative sum