Skip to content
Discussion options

You must be logged in to vote

We need to generate an array of n unique integers such that their sum is zero. The solution involves creating pairs of positive and negative integers that cancel each other out. If n is odd, we include zero to ensure the sum remains zero.

Approach

  1. Check for Odd n: If n is odd, we include zero in the result array. This is because zero does not affect the sum and helps in making the total number of elements odd.
  2. Generate Pairs: For the remaining even number of elements (if n was odd, we now have n-1 elements left), we generate pairs of positive and negative integers. For each integer i from 1 to n/2, we add i and -i to the result array. These pairs sum to zero, ensuring the overall sum of …

Replies: 1 comment 2 replies

Comment options

mah-shamim
Sep 7, 2025
Maintainer Author

You must be logged in to vote
2 replies
@kovatz
Comment options

kovatz Sep 7, 2025
Collaborator

@mah-shamim
Comment options

mah-shamim Sep 7, 2025
Maintainer Author

Answer selected by kovatz
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
question Further information is requested easy Difficulty
2 participants