Construct any array of length n containing distinct integers whose sum is exactly 0.
Problem
Given an integer n, build an array of exactly n distinct integers such that the sum of all elements is 0.
Any valid answer is accepted. There may be multiple correct outputs.
A simple construction is to pair positive and negative numbers so they cancel out, and include 0 when needed.
Input Format
- A single integer
n.
Output Format
- Return or print an array of
nunique integers whose total sum is0.
Constraints
1 <= n <= 1000- All integers in the answer must be distinct.
- The sum of all integers in the answer must be
0.
Hints
- Think about numbers in pairs like
xand-x. - If
nis odd, one value can be0and the remaining values can still be paired.
Input Format
- Integer
n.
Output Format
- An array of
ndistinct integers with sum0.
Constraints
1 <= n <= 1000- All elements must be unique.
- Sum of elements must be
0.
Example 1
Input
n = 5
Output
[-2,-1,0,1,2]
Explanation
All values are distinct and their sum is -2 + (-1) + 0 + 1 + 2 = 0.
Example 2
Input
n = 4
Output
[-2,-1,1,2]
Explanation
The numbers are unique and cancel out pairwise to make the sum 0.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.