Leetcode•Aug 04, 2025
Single Number II
Hazrat Ali
Leetcode
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,3,2] Output: 3
Example 2:
Input: nums = [0,1,0,1,0,1,99] Output: 99
Solution
/**
* @param {number[]} nums
* @return {number}
*/
const singleNumber = nums => {
let ones = 0,
twos = 0,
threes = 0;
for (let i = 0; i < nums.length; i++) {
twos |= ones & nums[i];
ones ^= nums[i];
threes = ones & twos;
ones &= ~threes;
twos &= ~threes;
}
return ones;
};