Given n numbers where every number appears three times except one which appears only once, find that single number (in linear time and space).
I’m sure everyone knows the two-number version — just use XOR.
Initially I used a map to solve it, but that didn’t feel like it met the problem’s intent. After reading others’ approaches, I realized it’s a variation of the same idea. I feel like I need to improve at generalizing solutions and analyzing problems.
The purpose of XOR is to count the number of 1s at each bit position, and reset to zero when the count reaches two.
Similarly, for three numbers, we reset to zero when the count reaches three.
Here is the code:
| |