Single Number II

medium bit manipulation

Problem

Given an integer array nums where every element appears three times except for one, which appears exactly once. Find the single element and return it.

Inputnums = [2,2,3,2]
Output3
Use two bitmasks ones and twos. For each bit position, count how many times it appears mod 3 across all numbers. The classic update keeps ones = bits seen 1 mod 3 times.

def single_number(nums):
    ones = twos = 0
    for x in nums:
        ones = (ones ^ x) & ~twos
        twos = (twos ^ x) & ~ones
    return ones
function singleNumber(nums) {
  let ones = 0, twos = 0;
  for (const x of nums) {
    ones = (ones ^ x) & ~twos;
    twos = (twos ^ x) & ~ones;
  }
  return ones;
}
class Solution {
    public int singleNumber(int[] nums) {
        int ones = 0, twos = 0;
        for (int x : nums) {
            ones = (ones ^ x) & ~twos;
            twos = (twos ^ x) & ~ones;
        }
        return ones;
    }
}
int singleNumber(vector<int>& nums) {
    int ones = 0, twos = 0;
    for (int x : nums) {
        ones = (ones ^ x) & ~twos;
        twos = (twos ^ x) & ~ones;
    }
    return ones;
}
Time: O(n) Space: O(1)