mediumBit ManipulationArrays & Hashing

Single Number II

mediumTime: O(n)Space: O(1)

Recognize the pattern

every element appears 3 times except onefind the unique elementbit counting modulo 3

Brute force idea

A straightforward first read of Single Number II is this: Hash map to count frequencies. Works but uses extra memory. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

The real unlock in Single Number II comes when you notice this: Count bits at each of 32 positions modulo 3. The unique number's bits are the remainders. Or use two variables (ones, twos) to track bit states. Instead of recomputing the world every time, you preserve just enough context to let the next decision become obvious.

Key invariant

The compass for Single Number II is this: If every number appears 3 times, each bit position has a total count divisible by 3. The unique number's contribution is the remainder when dividing each bit position's count by 3. As long as that statement keeps holding, you can trust the steps built on top of it.

Watch out for

The trap in Single Number II usually looks like this: Trying to use XOR like Single Number I — XOR only cancels pairs (appearing twice). For triples, you need modulo-3 bit counting. When the code becomes mechanical before the idea is clear, small edge cases start breaking the whole story.

Arrays & Hashing Pattern