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)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay