AlgoInsight

DSA problem

Single Number II

MediumBit ManipulationPattern: Bit Countingtop600AmazonGoogleMicrosoft

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

You must design an algorithm that runs in linear time and uses only constant extra space.

The classic XOR trick used for the "appears twice" version does not work here because three copies of a value do not cancel out. Instead, consider each of the 32 bit positions independently. If you sum the bit at a fixed position across all numbers, every value that appears three times contributes a multiple of three. Therefore, taking that sum modulo three leaves only the contribution of the unique number.

Reconstructing the answer one bit at a time from these mod-three counts yields the single element. A more elegant constant-space variant uses two bitmask accumulators that together track each bit count modulo three.

Examples

Example 1
Input: nums = [2,2,3,2]
Output: 3
Explanation: The value 2 appears three times and 3 appears once, so the single element is 3.
Example 2
Input: nums = [0,1,0,1,0,1,99]
Output: 99
Explanation: Both 0 and 1 appear three times; 99 appears once, so the answer is 99.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

bit-manipulationarraybit-counting

Browse all DSA problems