Single Number II (LeetCode 137): Solution and Explanation

Medium
Array
Bit Manipulation

Every value in nums appears three times except one, which appears once. Find the single value in linear time with constant extra space.

Intuition

In Single Number, where duplicates come in pairs, XOR of everything works because x ^ x = 0. With triples that breaks: x ^ x ^ x is x again, so the tripled values do not cancel.

Look at the numbers in binary, one bit column at a time. A value that appears three times adds three identical bits to its column, either three 0s or three 1s. So the number of 1s in any column is a multiple of 3, plus whatever the single number has there. Counting 1s modulo 3 gives the single number's bit.

You could count each of the 32 columns in a separate pass. The neater trick keeps the count for all columns in parallel. The count modulo 3 is 0, 1 or 2, which needs two bits per column, so use two integers: ones marks columns whose count is 1 and twos marks columns whose count is 2.

For each new number x, a column hit by x moves from 0 to 1, from 1 to 2, or from 2 back to 0. ones = (ones ^ x) & ~twos and twos = (twos ^ x) & ~ones implement exactly that cycle for every column in one shot. At the end every column with count 1 belongs to the single number, so ones is the answer.

Approach: Bitwise mod-3 counter with ones and twos

  1. Start with ones = 0 and twos = 0. Every column's count is 0.
  2. For each number x, update ones = (ones ^ x) & ~twos. Columns hit by x toggle in ones, except columns already at count 2.
  3. Then update twos = (twos ^ x) & ~ones. Columns hit by x toggle in twos, except columns that are now at count 1.
  4. A column hit for the third time ends with both bits cleared, so tripled values vanish.
  5. Return ones.

Step-by-step example

nums = [2,2,3,2]
  1. Start: ones = 00, twos = 00 (shown as the two low bits).
  2. x = 2 (10): ones = (00 ^ 10) & ~00 = 10, twos = (00 ^ 10) & ~10 = 00. Column 1 has count 1.
  3. x = 2 (10): ones = (10 ^ 10) & ~00 = 00, twos = (00 ^ 10) & ~00 = 10. Column 1 has count 2.
  4. x = 3 (11): ones = (00 ^ 11) & ~10 = 01, twos = (10 ^ 11) & ~01 = 00. Column 1 took its third hit and reset to 0; column 0 has count 1.
  5. x = 2 (10): ones = (01 ^ 10) & ~00 = 11, twos = (00 ^ 10) & ~11 = 00. Column 1 has seen four hits, and 4 mod 3 is 1.
  6. Both columns end at count 1, so ones = 11 = 3 and the function returns 3.

Code: Python, Java, C++

1class Solution:
2    def singleNumber(self, nums: List[int]) -> int:
3        ones, twos = 0, 0
4        for x in nums:
5            ones = (ones ^ x) & ~twos
6            twos = (twos ^ x) & ~ones
7        return ones
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

One pass over the array with a constant number of bitwise operations per element.

Space

O(1)

Two integers, ones and twos, regardless of the input size.

Other approaches

Hash map counts (time O(n), space O(n))

Count each value in a dictionary and return the key with count 1. Easy to get right but uses memory proportional to the number of distinct values.

Sum each bit position (time O(32n), space O(1))

For each of the 32 bit positions, count the 1s across all numbers and keep count % 3 as that bit of the answer. Same idea as the two registers, written as 32 explicit passes. Python needs care to rebuild a negative answer from bit 31.

Set math (time O(n), space O(n))

Compute (3 * sum(set(nums)) - sum(nums)) / 2. Short, but it builds a set and can overflow in fixed-width languages.

Common mistakes

  • Using plain XOR as in Single Number. With triples, each repeated value survives instead of cancelling.
  • Updating twos before ones, or using the old ones in the twos line. The order and the fresh value of ones are what make the 0 to 1 to 2 to 0 cycle work.
  • In the per-bit-sum version in Python, forgetting that bit 31 set means a negative number. Python ints do not wrap, so subtract 2^32 when the result is at least 2^31.
  • Assuming the inputs are non-negative. Negative numbers set high bits, and the counters must handle every bit, which the two-register method does automatically.

Frequently asked questions

Why does ones end up holding the answer?

Each column's count of 1s is 3k plus the single number's bit. Modulo 3 that is 0 or 1, never 2, so twos ends at 0 and ones has a 1 exactly where the single number does.

Does this work for negative numbers?

Yes. The updates are independent per bit, so the sign bit is just another column. In Python, ints behave like infinitely sign-extended two's complement, so a negative single number comes out negative without any fix-up.

Can the same trick handle values that appear k times?

Yes. Count each column modulo k. For k = 3 two bits per column suffice; larger k needs more registers or the explicit per-bit counting loop.

How is this different from Single Number?

Single Number has pairs, and XOR is a counter modulo 2 for every column. Single Number II needs a counter modulo 3, which takes two bits per column instead of one.