#137

Single Number II

Medium Bit counting

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Every number appears three times except one, which appears once. Find it with O(1) extra space.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: every number appears three times except one.

Why this works: look at one bit position at a time. The triplets add a multiple of 3 to that bit's count, so count % 3 is the single number's bit.

Example: [2, 2, 3, 2] → binary 10, 10, 11, 10

bit 0: 0+0+1+0 = 1 → 1 % 3 = 1bit 1: 1+1+1+1 = 4 → 4 % 3 = 1answer 11 = 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Using a HashMap of counts — correct but O(n) space.