Single Number II
Difficulty: Medium · Pattern: Bit Manipulation · LeetCode #137
Every element appears three times except one, which appears exactly once. Find that one in O(n) time and O(1) extra space.
Examples
text
[2,2,3,2] → 3
[0,1,0,1,0,1,99] → 99
[-2,-2,1,1,4,1,4,4,-4,-2] → -4Hints
- XOR alone cancels pairs, not triples.
- Look at each bit position separately. Count the ones there. Mod 3, what remains?
Approach
Bit counting: for each of the 32 bits, sum that bit across all numbers. Triples contribute multiples of 3, so count % 3 is the single number's bit. Rebuild the number from those bits. For negative numbers, bit 31 is the sign: in Python, subtract 2³² if the result ≥ 2³¹.
Constant-time-per-element state machine (an elegant alternative):
text
ones = (ones ^ x) & ~twos
twos = (twos ^ x) & ~onesones/twos hold the bits seen 1 or 2 times (mod 3). The answer ends up in ones.
Complexity
Time: O(n) (32·n for bit counting). Space: O(1).
Python solution
def singleNumber(nums):
ones = twos = 0
for x in nums:
ones = (ones ^ x) & ~twos
twos = (twos ^ x) & ~ones
return onesJavaScript solution
function singleNumber(nums) {
let res = 0;
for (let b = 0; b < 32; b++) {
let cnt = 0;
for (const x of nums) cnt += (x >> b) & 1;
if (cnt % 3) res |= 1 << b;
}
return res | 0; // interpret as signed 32-bit
}