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

268 Missing Numbers

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

/*
 * Given an array containing n distinct numbers taken from 0, 1, 2, ..., n,
 * find the one that is missing from the array.
 *
 * Example 1:
 * Input: [3,0,1]
 * Output: 2
 *
 * Example 2:
 * Input: [9,6,4,2,3,5,7,0,1]
 * Output: 8
 */

function missingNumbers(value) {
  let target = 0
  for (let index = 1; index <= value.length; index++) {
    target += index    
  }

  for (let index = 0; index < value.length; index++) {
    target -= value[index]    
  }

  return target
}

test('missing Numbers', () => {
  expect(missingNumbers([3, 0, 1])).toEqual(2)
  expect(missingNumbers([9, 6, 4, 2, 3, 5, 7, 0, 1])).toEqual(8)
})

Created 2020-04-18T22:16:20+00:00 · Edit