Talentd
FleetCode
Make and follow sheets.Sign in

Find N Unique Integers Sum up to Zero solution and explanation

EasyArrayMath5 min read78.5% acceptanceUpdated 14 Apr 2026
Find N Unique Integers Sum up to Zero | 2 Easy Ways | Leetcode 1304 | codestorywithMIKcodestorywithMIK · 9:30 · 4K viewsWatch on YouTube
9 more videos on this problem
  1. Find N Unique Integers Sum up to Zero | 2 Easy Ways | Leetcode 1304 | codestorywithMIKcodestorywithMIK · 9:30 · 4K views
  2. Leetcode 1304: Find N Unique Integers Sum up to ZeroAlgorithms Casts · 9:19 · 3K views
  3. FIND N UNIQUE INTEGERS WHICH SUM TO ZERO | LEETCODE # 1304 | PYTHON SOLUTIONCracking FAANG · 8:25 · 2K views
  4. 1304. Find N Unique Integers Sum up to Zero | Leetcode Daily - PythonLeetcode Daily · 4:31 · 1K views
  5. LeetCode 1304 : Find N Unique Integers Sum up to Zero | Solution in JAVAAmit Manjarly · 7:14 · 858 views
  6. Find N Unique Integers Sum up to Zero | LeetCode 1304 | Java Code | Developer CoderDeveloper Coder · 4:10 · 452 views
  7. Daily Leetcode #1986: Sep 07, 2025 - 1304. Find N Unique Integers Sum up to ZeroProgramming Live with Larry · 2:59 · 402 views
  8. Find N Unique Integers Sum up to Zero - Leetcode 1304 JavaScript Solution and AlgorithmVitaly · 7:22 · 308 views
  9. LeetCode 1304 : Find N Unique Integers Sum up to Zero | Solution in C++Amit Manjarly · 6:06 · 297 views
  10. 1304. Find N Unique Integers Sum up to Zero Leetcode/ Explanation + code /C++Coding with U · 6:06 · 280 views

The problem

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

Example 1:

Input: n = 5
Output: [-7,-1,1,3,4]
Explanation: These arrays also are accepted [-5,-1,1,2,3] , [-3,-1,2,-2,4].

Example 2:

Input: n = 3
Output: [-1,0,1]

Example 3:

Input: n = 1
Output: [0]

Constraints:

  • 1 <= n <= 1000

Approach overview

Problem Overview: You need to construct an array of n unique integers such that their total sum equals zero. The values can be any integers as long as they are distinct and the final sum is exactly 0. Because the order does not matter and many valid answers exist, the goal is simply to generate one correct combination efficiently.

Approach 1: Use Symmetric Pairing (O(n) time, O(n) space)

The simplest observation is that every positive number x cancels out with -x. Using this symmetry, you can construct pairs like (1, -1), (2, -2), and continue until you fill the array. Iterate from 1 to n/2 and append both i and -i to the result array. If n is odd, add a single 0 at the end since zero does not affect the sum and remains unique. The algorithm only requires a single pass to build the result, giving O(n) time complexity and O(n) space for the output array. This method works well because it directly exploits arithmetic symmetry instead of searching for combinations. Problems involving array construction often benefit from such mathematical observations. If you are practicing array manipulation patterns, see more examples under Array problems.

Approach 2: Consecutive Integers Strategy (O(n) time, O(n) space)

Another clean construction uses consecutive integers centered around zero. Generate numbers from -(n/2) up to n/2 while skipping zero when necessary to maintain uniqueness and the correct count. A common implementation builds values from 1 to n-1 and keeps a running sum, then adds the final value as -sum. Because the earlier values are distinct, the last number guarantees the total becomes zero. The loop runs once, so the time complexity is O(n) and the extra space used is O(n). This approach highlights a useful trick in Math-based problems: control the running sum and adjust the final element to satisfy the constraint.

Recommended for interviews: The symmetric pairing method is what most interviewers expect. It shows you immediately recognized the mathematical structure of the problem and produced a clean O(n) construction without unnecessary bookkeeping. The consecutive integer strategy is also valid and demonstrates comfort with array generation and running-sum reasoning. If you mention both approaches during discussion, it signals strong problem-solving depth even for an easy-level question.

Approach 1: Use Symmetric Pairing

This approach involves using numbers in symmetric pairs to achieve the sum of zero. For example, if n is even, you can use pairs like (-1, 1), (-2, 2), etc. If n is odd, include zero to the list to keep the sum zero.

def sumZero(n):
    result = []
    for i in range(1, n // 2 + 1):
        result.append(i)
        result.append(-i)
    if n % 2 != 0:
        result.append(0)
    return result
import java.util.*;

public class SumZero {
    public int[] sumZero(int n) {
        int[] result = new int[n];
        int index = 0;
        for (int i = 1; i <= n / 2; ++i) {
            result[index++] = i;
            result[index++] = -i;
        }
        if (n % 2 != 0) {
            result[index] = 0;
        }
        return result;
    }
}
#include <vector>

std::vector<int> sumZero(int n) {
    std::vector<int> result;
    for (int i = 1; i <= n / 2; ++i) {
        result.push_back(i);
        result.push_back(-i);
    }
    if (n % 2 != 0) {
        result.push_back(0);
    }
    return result;
}
function sumZero(n) {
    let result = [];
    for (let i = 1; i <= n / 2; i++) {
        result.push(i);
        result.push(-i);
    }
    if (n % 2 !== 0) {
        result.push(0);
    }
    return result;
}
#include <stdio.h>
#include <stdlib.h>

int* sumZero(int n, int* returnSize) {
    int* result = (int*)malloc(n * sizeof(int));
    *returnSize = n;
    int index = 0;
    for (int i = 1; i <= n / 2; ++i) {
        result[index++] = i;
        result[index++] = -i;
    }
    if (n % 2 != 0) {
        result[index] = 0;
    }
    return result;
}
using System;

public class SumZero
{
    public int[] GetSumZeroArray(int n)
    {
        int[] result = new int[n];
        int index = 0;
        for (int i = 1; i <= n / 2; ++i)
        {
            result[index++] = i;
            result[index++] = -i;
        }
        if (n % 2 != 0)
        {
            result[index] = 0;
        }
        return result;
    }
}

The Python solution makes use of a list to append integer pairs. If n is odd, zero is appended.

Complexity

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

Try this approach in the editor

Approach 2: Consecutive Integers Strategy

This approach utilizes consecutive integers starting from 1-n and converting half to negative. The sequence is constructed such that all elements are positive in the first half and their negative counterparts in the second, ensuring zero sum.

def sumZero(n):
    result = [i + 1 for i in range(n - 1)]
    result.append(-sum(result))
    return result
import java.util.*;

public class SumZero {
    public int[] sumZero(int n) {
        int[] result = new int[n];
        int sum = 0;
        for (int i = 0; i < n - 1; ++i) {
            result[i] = i + 1;
            sum += result[i];
        }
        result[n - 1] = -sum;
        return result;
    }
}
#include <vector>

std::vector<int> sumZero(int n) {
    std::vector<int> result(n);
    int sum = 0;
    for (int i = 0; i < n - 1; ++i) {
        result[i] = i + 1;
        sum += result[i];
    }
    result[n - 1] = -sum;
    return result;
}
function sumZero(n) {
    let result = [];
    let sum = 0;
    for (let i = 0; i < n - 1; i++) {
        result.push(i + 1);
        sum += i + 1;
    }
    result.push(-sum);
    return result;
}
#include <stdio.h>
#include <stdlib.h>

int* sumZero(int n, int* returnSize) {
    int* result = (int*)malloc(n * sizeof(int));
    *returnSize = n;
    int sum = 0;
    for (int i = 0; i < n - 1; ++i) {
        result[i] = i + 1;
        sum += result[i];
    }
    result[n - 1] = -sum;
    return result;
}
using System;

public class SumZero
{
    public int[] GetSumZeroArray(int n)
    {
        int[] result = new int[n];
        int sum = 0;
        for (int i = 0; i < n - 1; ++i)
        {
            result[i] = i + 1;
            sum += result[i];
        }
        result[n - 1] = -sum;
        return result;
    }
}

Python uses a list comprehension for concise code. The last element is computed to offset the sum of the preceding integers.

Complexity

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

Try this approach in the editor

Approach 3: Construction

We can start from 1 and alternately add positive and negative numbers to the result array. We repeat this process \frac{n}{2} times. If n is odd, we add 0 to the result array at the end.

The time complexity is O(n), where n is the given integer. Ignoring the space used for the answer, the space complexity is O(1).

function sumZero(n: number): number[] {
    const ans: number[] = Array(n).fill(0);
    for (let i = 1, j = 0; i <= n / 2; ++i) {
        ans[j++] = i;
        ans[j++] = -i;
    }
    return ans;
}
func sumZero(n int) []int {
	ans := make([]int, n)
	for i, j := 1, 0; i <= n/2; i, j = i+1, j+1 {
		ans[j] = i
		j++
		ans[j] = -i
	}
	return ans
}
impl Solution {
    pub fn sum_zero(n: i32) -> Vec<i32> {
        let mut ans = vec![0; n as usize];
        let mut j = 0;
        for i in 1..=n / 2 {
            ans[j] = i;
            j += 1;
            ans[j] = -i;
            j += 1;
        }
        ans
    }
}
Try this approach in the editor

Approach 4: Construction + Mathematics

We can also add all integers from 1 to n-1 to the result array, and finally add the opposite of the sum of the first n-1 integers, which is -\frac{n(n-1)}{2}, to the result array.

The time complexity is O(n), where n is the given integer. Ignoring the space used for the answer, the space complexity is O(1).

function sumZero(n: number): number[] {
    const ans = new Array(n).fill(0);
    for (let i = 1; i < n; ++i) {
        ans[i] = i;
    }
    ans[0] = -((n * (n - 1)) / 2);
    return ans;
}
func sumZero(n int) []int {
	ans := make([]int, n)
	for i := 1; i < n; i++ {
		ans[i] = i
	}
	ans[0] = -n * (n - 1) / 2
	return ans
}
impl Solution {
    pub fn sum_zero(n: i32) -> Vec<i32> {
        let mut ans = vec![0; n as usize];
        for i in 1..n {
            ans[i as usize] = i;
        }
        ans[0] = -(n * (n - 1) / 2);
        ans
    }
}
Try this approach in the editor

Complexity comparison

ApproachComplexity
Use Symmetric Pairing

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

Consecutive Integers Strategy

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

Construction–
Construction + Mathematics–

Complexity analysis

ApproachTimeSpaceWhen to Use
Symmetric PairingO(n)O(n)Best general solution. Simple construction using positive and negative pairs.
Consecutive Integers StrategyO(n)O(n)Useful when reasoning with running sums or constructing numbers sequentially.

Frequently asked questions

Is Find N Unique Integers Sum up to Zero easy or hard?

Find N Unique Integers Sum up to Zero is classified as an Easy problem on LeetCode with an acceptance rate around 78%. The challenge mainly checks whether you recognize the symmetric property of integers that cancel each other out.

Find N Unique Integers Sum up to Zero Python/Java solution

In Python or Java, create an array and add symmetric pairs like i and -i while iterating from 1 to n/2. If n is odd, append 0. The implementation requires only a loop and basic array operations, so the code remains concise across languages.

How to solve Find N Unique Integers Sum up to Zero in O(n)?

Iterate from 1 to n/2 and insert both i and -i into the result array. These pairs cancel each other and maintain uniqueness. If n is odd, append 0 at the end. This single pass produces n numbers with total sum zero in linear time.

What is the best approach for Find N Unique Integers Sum up to Zero?

The symmetric pairing approach is the most straightforward solution. Generate pairs like (1, -1), (2, -2), and continue until you fill the array. If n is odd, add 0 as the final element. This guarantees all numbers are unique and the total sum is zero while running in O(n) time.

Is Find N Unique Integers Sum up to Zero asked at Google/Amazon/Meta?

This problem is tagged as an easy array and math question and appears frequently in interview preparation sets. Variations of constructive array problems are commonly asked by companies like Google, Amazon, and Meta to test logical reasoning and basic algorithm design.

What data structure is used in Find N Unique Integers Sum up to Zero?

The solution mainly uses a simple array or list to store the generated integers. The logic relies more on mathematical symmetry than advanced data structures, which keeps the implementation short and efficient.

What is the time complexity of Find N Unique Integers Sum up to Zero?

The optimal construction runs in O(n) time because you generate each element exactly once. Space complexity is also O(n) since the result array must store n integers. No additional data structures or nested loops are required.

Comments

Now write it yourselfClose this page and solve Find N Unique Integers Sum up to Zero in the editor, without looking.
Practise Find N Unique Integers Sum up to Zero