Single Number II

Medium

Topics
ArrayBit Manipulation

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

Example 1

nums2232
76543210200000010200000010300000011200000010
Every value appears three times except one. Plain XOR no longer cancels, so the count is taken per bit, modulo 3: any bit left non-zero belongs to the lone value, 3. The compact version keeps two bitmasks as a mod-3 counter.
Top row is the input; below it the binary expansion of each value.
Input:  nums = [2,2,3,2]
Output: 3

Example 2

nums01010199
76543210000000000100000001000000000100000001000000000100000001
Input:  nums = [0,1,0,1,0,1,99]
Output: 99

Constraints

  • 1 <= nums.length <= 3*10^4
  • Each element appears 3x except one which appears once.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Every value except one appears three times, so for each bit position the total count of ones is a multiple of three plus the contribution of the answer. Summing each bit independently and taking it modulo three recovers the answer — that is the version to describe first, because it is obviously correct and it generalises to any repeat count.

The shown solution is the two-variable form of the same idea: a pair of masks acting as a mod-three counter, one bit per position. ones holds the bits seen once so far, twos the bits seen twice, and a third sighting clears both. The order of the two updates matters, because the second reads the ones the first just produced.

Approach

  1. Start ones and twos at zero.
  2. For each value, set ones = (ones ^ x) & ~twos.
  3. Then set twos = (twos ^ x) & ~ones, using the freshly updated ones.
  4. After the pass, ones holds the value seen exactly once.

Dry Run

nums = [2,2,3,2]

  x   ones    twos
  2   0b10    0b0      first sighting of bit 1
  2   0b0     0b10     second sighting moves it to twos
  3   0b1     0b0      bit 0 is new; bit 1 reaches three and clears
  2   0b11    0b0      hmm -- bit 1 is seen a fourth time, so the cycle restarts

answer 3

  [0,1,0,1,0,1,99]  -> 99
  [-2,-2,1,-2]      -> 1      negatives work too

Complexity

  • Time — O(n): one pass, two bitwise updates per element.
  • Space — O(1): two integers, which is what the problem demands.
  • The bit-count-modulo-three variant is also O(n) time and O(1) space — 32 fixed counters — and is far easier to defend under questioning.

Common Pitfalls

  • Swapping the two update lines. twos must be computed from the new ones; reversing them breaks the mod-three cycle.
  • Reaching for a hash map of counts. Correct and O(n) time, but O(n) space, and the problem asks for constant extra space.
  • XOR-ing everything, as in single number I. XOR cancels pairs, not triples, so it returns garbage here.
  • Assuming the input is non-negative. In a fixed-width language the masks handle the sign bit like any other bit; in Python the arbitrary-precision ~ still gives the right answer, verified on [-2,-2,1,-2].
  • In the bit-counting variant, forgetting to sign-extend the reconstructed value. If bit 31 survives the modulo, the result is negative and must be interpreted as such rather than as a large positive.
  • Presenting the two-mask form without deriving it. It is effectively unguessable, and an interviewer will ask where it comes from — the mod-three counter is the derivation.

Full Solution — all languages

class Solution:
    def singleNumber(self, nums):
        ones = twos = 0
        for x in nums:
            ones = (ones ^ x) & ~twos
            twos = (twos ^ x) & ~ones
        return ones
SensAI
Beta
Tap the mic to stop voice mode