Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created September 7, 2025 16:58
Show Gist options
  • Select an option

  • Save tatsuyax25/51374a508142eeb5ec9555be2fed7798 to your computer and use it in GitHub Desktop.

Select an option

Save tatsuyax25/51374a508142eeb5ec9555be2fed7798 to your computer and use it in GitHub Desktop.
Given an integer n, return any array containing n unique integers such that they add up to 0.
/**
* @param {number} n
* @return {number[]}
*/
var sumZero = function(n) {
const result = [];
// Add symmetric pairs: [-1, 1], [-2, 2], ...
for (let i = 1; i <= Math.floor(n / 2); i++) {
result.push(-i, i)
}
// If n is odd, include 0 to balance the sum
if (n % 2 !== 0) {
result.push(0);
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment