Every number appears three times except one. Count each of the 32 bits across the array; a count that isn't a multiple of 3 belongs to it.
▼The problem
LeetCode 137 (Medium). Every element of nums appears exactly three times except one, which appears once. Find that single one in O(n) time and O(1) extra space.
Example: [5, 3, 5, 5] → 3.
The solution
def singleNumber(nums):
ans = 0
for b in range(32):
cnt = sum((x >> b) & 1 for x in nums)
if cnt % 3:
ans |= 1 << b
if ans >= 1 << 31: # sign bit set
ans -= 1 << 32
return ansTranscript
Single Number Two. Every number in the list appears three times, except one, which appears just once. Find it. The catch: linear time, and only constant extra space.
Take five, three, five, five. Five shows up three times, and three shows up once, so the answer is three.
The easy way counts every number in a hash map and returns the one with a count of one. That's linear time, but the map grows with the input. Sorting needs no map, but it costs n log n.
And the XOR trick from Single Number fails here. XOR cancels pairs: five XOR five is zero. Three fives, though, XOR back to five, so the whole list gives six, not three.
So count bits instead. Give each bit position a tray. Every number with that bit set drops a cookie in, and the baker packs cookies in boxes of three. A number that appears three times fills whole boxes and leaves nothing behind. So whatever is left in a tray, the count mod three, is the single number's bit.
Let's bake five, three, five, five. Five is one zero one, and three is zero one one. The first five drops cookies in the fours and the ones. Three drops into the twos and the ones. The second five makes three in the ones tray: box them. The last five fills the fours tray, another box, and leaves one in the ones. Left over: zero, one, one. That's three.
In code, loop over all thirty-two bit positions. Count how many numbers have that bit set. If the count mod three isn't zero, set that bit in the answer. One catch: Python integers don't wrap at thirty-two bits, so if the sign bit is set, subtract two to the thirty-two to get the negative number back.
That's thirty-two passes over n numbers, which is order n time. The only memory is a few counters, so the space is order one.
Count each bit, keep it mod three, rebuild the number. That's Single Number Two.