SDE & MLE Prep

137. Single Number II

Problem

Every value in nums appears three times except one, which appears once. Return that one, in O(n) time and O(1) extra space.

Example: [2,2,3,2] → 3; [0,1,0,1,0,1,99] → 99

Every other number appears 3 times → for each bit position, the count of set bits mod 3 is the single number's bit. (Handle the sign bit for negatives in Python.)

Complexity: O(32·n).

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        res = 0
        for b in range(32):
            if sum((x >> b) & 1 for x in nums) % 3:
                res |= 1 << b
        return res - (1 << 32) if res >= 1 << 31 else res