Find N Unique Integers Sum up to Zero - Problem

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

The array should contain exactly n distinct integers, and their sum must equal zero. You can return any valid combination that satisfies these constraints.

Note: There are multiple valid answers for each input, so any correct solution will be accepted.

Input & Output

Example 1 — Even Number
$ Input: n = 4
Output: [1,-1,2,-2]
💡 Note: Create 2 pairs of opposite numbers: (1,-1) and (2,-2). Sum: 1 + (-1) + 2 + (-2) = 0
Example 2 — Odd Number
$ Input: n = 5
Output: [0,1,-1,2,-2]
💡 Note: Since n is odd, add 0 first, then create 2 pairs: (1,-1) and (2,-2). Sum: 0 + 1 + (-1) + 2 + (-2) = 0
Example 3 — Minimum Case
$ Input: n = 1
Output: [0]
💡 Note: Only one unique integer that sums to zero is 0 itself

Constraints

  • 1 ≤ n ≤ 1000

Visualization

Tap to expand
Find N Unique Integers Sum up to Zero INPUT n = 4 (integer input) Need 4 unique integers ? ? ? ? Constraint: Sum must equal 0 Input Value: n = 4 ALGORITHM STEPS 1 Pair Strategy Use pairs: i and -i 2 Generate Pairs For i=1 to n/2: add i,-i 3 Handle Odd n If n is odd, add 0 4 Return Array All pairs sum to 0 For n=4: 1 + -1 = 0 2 + -2 = 0 FINAL RESULT Output Array: 1 -1 2 -2 Verification: 1 + (-1) + 2 + (-2) = 0 [OK] Output: [1, -1, 2, -2] 4 unique integers Sum = 0 [OK] Key Insight: The optimal approach uses pairs of positive and negative numbers (i and -i). Each pair sums to zero, so any combination of pairs will also sum to zero. For odd n, simply include 0 in the array. Time Complexity: O(n) | Space Complexity: O(n) TutorialsPoint - Find N Unique Integers Sum up to Zero | Optimal Solution
Asked in
Google 15 Microsoft 12 Amazon 8
33.4K Views
Medium Frequency
~8 min Avg. Time
856 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen