code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

1304 Find N Unique Integers Sum Up To Zero

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

/*
 * 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]
 */

function findNUniqueIntegersSumUpToZero(n) {
  let result = n % 2 === 0 ? [n, -n] : [0]
  for (let index = 1; index < n / 2; index++) {
    result.push(index, -index)
  }
  return result
}

test('find N Unique Integers Sum Up To Zero', () => {
  expect(findNUniqueIntegersSumUpToZero(5)).toEqual([0, 1, -1, 2, -2])
})

Created 2020-04-20T21:48:53+00:00 · Edit