mediumBit ManipulationArrays & Hashing

Single Number II

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

Signals to notice

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

Brute force first

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.

The key insight

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.

What must stay true

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.

Easy way to go wrong

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