Algo-Sim › Matrix & Bit Manipulation

Single Number II

Medium · Matrix & Bit Manipulation · step through it in Java, Python and C++ on your own input

Every number appears three times except one. Count the 1s in each bit column mod 3: the leftovers are the single number’s bits.

Problem

In the array nums, every value appears exactly three times except one, which appears once. Return that value, in linear time and constant extra space.

Constraints

Edge cases to test

Follow-up questions

How does the ones/twos trick work?
They hold the bits seen once and twice mod 3: ones = (ones ^ x) & ~twos, twos = (twos ^ x) & ~ones. O(n), O(1).
How does it generalise?
For values repeated k times, count each bit mod k: O(32·n) time, O(1) space.

Solution

Java

public int singleNumber(int[] nums) {
    int result = 0;
    for (int bit = 0; bit < 32; bit++) {
        int count = 0;
        for (int num : nums) count += (num >> bit) & 1;
        // Triples add 0 mod 3; only the single number's bit is left over.
        if (count % 3 != 0) result |= 1 << bit;
    }
    return result;
}

Python

def single_number(nums):
    result = 0
    for bit in range(32):
        count = sum((num >> bit) & 1 for num in nums)
        # Triples add 0 mod 3; only the single number's bit is left over.
        if count % 3:
            result |= 1 << bit
    # Python ints are unbounded: bit 31 set means a negative 32-bit answer.
    return result - (1 << 32) if result >= 1 << 31 else result

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    int singleNumber(vector<int> &nums) {
        unsigned result = 0;
        for (int bit = 0; bit < 32; bit++) {
            int count = 0;
            for (int num : nums) count += (unsigned(num) >> bit) & 1;
            // Triples add 0 mod 3; only the single number's bit is left over.
            if (count % 3 != 0) result |= 1u << bit;
        }
        return int(result);
    }
};

More Matrix & Bit Manipulation problems