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

136 Single Number

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

/* 
 * Given a non-empty array of integers, every element appears twice
 * except for one. Find that single one.
 * 
 * Example 1:
 * Input: [2,2,1]
 * Output: 1
 */

function singleNumber(value) {
  let result = 0
  for (let i = 0; i < value.length; i++) {
    result = result ^ value[i]    
  }
  return result
}

test('single Number', () => {
  expect(singleNumber([2,2,1])).toEqual(1)
});

Created 2020-04-19T20:33:48+00:00, updated 2020-04-25T12:47:10+00:00 · History · Edit