DEV Community

Cover image for Single Lonely Number
chandra penugonda
chandra penugonda

Posted on

Single Lonely Number

In a given array of numbers, one element will show up once and the others will each show up twice. Can you find the number that only appears once in O(n) linear time? Bonus points if you can do it in O(1) space as well.

Example

lonelyNumber([4, 4, 6, 1, 3, 1, 3]) // 6

lonelyNumber([3, 3, 9])// 9
Enter fullscreen mode Exit fullscreen mode

Solution 1

function lonelyNumber(nums){
    const obj={}
    for(const num of nums){
        obj[num]= (obj[num]||0)+1
    }
    for(const num in obj){
        if(obj[num]===1) return num
    }
}

console.log(lonelyNumber([4, 4, 6, 1, 3, 1, 3])); // 6
console.log(lonelyNumber([3, 3, 9])); // 9
Enter fullscreen mode Exit fullscreen mode

Solution 2

function lonelyNumber(numbers) {
  return numbers.reduce((x, y) => x ^ y, 0);
}

console.log(lonelyNumber([4, 4, 6, 1, 3, 1, 3])); // 6
console.log(lonelyNumber([3, 3, 9])); // 9
Enter fullscreen mode Exit fullscreen mode

Top comments (0)