singleNumber

Medium · Bit Manipulation · 3 test cases

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Examples

singleNumber([2, 2, 1]) → 1
singleNumber([4, 1, 2, 1, 2]) → 4

Starter code

function singleNumber(nums) {

}

Complexity of the optimal solution

Time O(n), space O(1). This solution leverages the property of XOR where `x ^ x = 0` and `x ^ 0 = x`. By XORing all numbers in the array, the duplicate numbers cancel each other out, leaving only the unique number. This requires one pass through the array (O(n) time) and constant extra space.

Solve singleNumber in the browser