Single Number II

medium

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

Your solution must run in linear time and use only constant extra space.

Hints

XOR made pairs vanish because it counts each bit mod 2. What changes when copies come in threes?
Look at one bit position at a time across every number.
Sum each bit column and take it mod 3 — the tripled values contribute a multiple of 3 and disappear.

Common doubts

XOR tracks each bit's parity (mod 2), so a value appearing three times still flips the bit to 1. Counting the bit column mod 3 makes any thrice-appearing value contribute 0.
Values fit in 32-bit signed integers. Bits 0-30 are magnitude and bit 31 is the sign; rebuilding all 32 and reading the pattern as signed recovers negative answers correctly.
32 is a constant (the integer width), so 32*n is still linear. The win is dropping the O(n) map down to O(1) space.

Interview follow-ups

Same idea, generalized: count each bit column mod k. Whatever appears k times contributes a multiple of k and cancels, leaving the unique element's bits.
Yes — track two bitmask accumulators (ones, twos) that record how many times, mod 3, each bit has been seen. It's the same constant-space guarantee in a single pass.

Fun facts

  • This 'count mod k' trick is a digital-circuit staple: a mod-3 counter per bit line does exactly this in hardware.
  • The two-accumulator ones/twos version is essentially a ternary finite-state machine running in parallel across all 32 bit positions.

Asked at

AmazonGoogleMicrosoftAdobe
Frequently Sometimes Occasionally
Example 1
Input: nums = [2, 2, 3, 2]
Output: 3
2 appears three times and cancels column-by-column; 3 is the single value.
Example 2
Input: nums = [0, 1, 0, 1, 0, 1, 99]
Output: 99
0 and 1 each appear three times; 99 is the only element appearing once.
Example 3
Input: nums = [1]
Output: 1
A lone element is trivially the single one.
Constraints

- 1 <= nums.length <= 3 * 10^4 - -2^31 <= nums[i] <= 2^31 - 1 - Every element appears exactly three times except for one element which appears once.

Solve this problem →