LeetCode #137 Medium

Single Number II

Single Number II is LeetCode 137 (Medium). Every element of nums appears exactly three times except one, which appears once. Return that one.

  • Run in O(n) time with O(1) extra space.
  • Values cover the whole 32-bit signed range, so the answer can be negative.

A hash map of counts finds the answer easily, but it uses O(n) memory. The constant-space rule is what makes this Medium.

Constraints
  • 1 <= nums.length <= 3 * 10⁴
  • -2³¹ <= nums[i] <= 2³¹ - 1
  • Each element in nums appears exactly three times except for one element which appears once.
bit-manipulationarrayxor
Open on LeetCode ↗
02

Intuition

In the easier version (LeetCode 136) every other value appears twice, and XOR cancels each pair. Three copies do not cancel: a ^ a ^ a is a again. So stop looking at whole numbers and look at one bit position at a time.

  • A value seen three times adds either 0 or 3 ones to that position, always a multiple of 3.
  • The lone value adds one more 1 wherever its own bit is set.

So in every position, the count of ones, divided by 3, leaves exactly the lone number's bit. Doing this for all 32 positions rebuilds the number.

How to spot this pattern

"Every value repeats k times except one" together with an O(1) memory limit points to counting bits per position and keeping the remainder after dividing by k. The same loop works for any k, not just 3.

03

Approach

Try it first

Before reading on, write the numbers in binary, one under another, and count the ones in each column. What do the counts have in common, and what does the lone number change? Aim for O(n) time and O(1) space.

1

Count the ones in one bit position

For each bit i from 0 to 31, loop over nums and add (n >> i) & 1 to count. Shifting right by i brings bit i to the end, and & 1 reads it as 0 or 1.

2

Keep the bit when the count is not a multiple of 3

If count % 3 is not 0, set bit i of the answer with ans |= 1 << i. Every tripled value added 0 or 3 to the count, so a remainder of 1 can only come from the lone number.

3

Turn bit 31 back into a sign

Bit 31 is the sign bit. Java and C++ keep the answer in 32 bits, so setting it already makes the number negative. Python integers have no fixed width, so if ans >= 2³¹ the code subtracts 2³² to get the negative value back.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def singleNumber(self, nums):
▶3 ans = 0
▶4 for i in range(32):
▶5 count = 0
▶6 for n in nums:
▶7 count += (n >> i) & 1
▶8 if count % 3:
▶9 ans |= 1 << i
▶10 if ans >= 1 << 31:
▶11 ans -= 1 << 32
▶12 return ans
bit 0bit 1nums201201311201countans=0answer starts with no bits set
ans0
Each number is written in binary, one per row. Columns are bit positions. Instead of comparing whole numbers, the loop will count the 1s in one column at a time. Columns above bit 1 hold only 0s here, so they are not drawn.
bit 0bit 1nums201201311201count0ans=02 has no bit 0 → count stays 0
i0bit position
n2binary 10
count0
Shift 2 right by 0 and keep the last bit: it is 0. Nothing to add, so the count stays at 0.
bit 0bit 1nums201201311201count0ans=02 has no bit 0 → count stays 0
i0bit position
n2binary 10
count0
Shift 2 right by 0 and keep the last bit: it is 0. Nothing to add, so the count stays at 0.
bit 0bit 1nums201201311201count1ans=03 has bit 0 set → count 1
i0bit position
n3binary 11
count1
Shift 3 right by 0 and keep the last bit: it is 1. So column 0 has one more 1, and the count rises to 1.
bit 0bit 1nums201201311201count1ans=02 has no bit 0 → count stays 1
i0bit position
n2binary 10
count1
Shift 2 right by 0 and keep the last bit: it is 0. Nothing to add, so the count stays at 1.
bit 0bit 1nums201201311201count1ans1=1count 1 → 1 left over after threes → set bit 0
count % 31
ans1 in binary
Every value that appears three times put 0 or 3 ones into this column. Taking out all full groups of 3 from 1 leaves 1, and only the lone number can supply it, so bit 0 of the answer is 1.
bit 0bit 1nums201201311201count11ans1=12 has bit 1 set → count 1
i1bit position
n2binary 10
count1
Shift 2 right by 1 and keep the last bit: it is 1. So column 1 has one more 1, and the count rises to 1.
bit 0bit 1nums201201311201count12ans1=12 has bit 1 set → count 2
i1bit position
n2binary 10
count2
Shift 2 right by 1 and keep the last bit: it is 1. So column 1 has one more 1, and the count rises to 2.
bit 0bit 1nums201201311201count13ans1=13 has bit 1 set → count 3
i1bit position
n3binary 11
count3
Shift 3 right by 1 and keep the last bit: it is 1. So column 1 has one more 1, and the count rises to 3.
bit 0bit 1nums201201311201count14ans1=12 has bit 1 set → count 4
i1bit position
n2binary 10
count4
Shift 2 right by 1 and keep the last bit: it is 1. So column 1 has one more 1, and the count rises to 4.
bit 0bit 1nums201201311201count14ans11=3count 4 → 1 left over after threes → set bit 1
count % 31
ans11 in binary
Every value that appears three times put 0 or 3 ones into this column. Taking out all full groups of 3 from 4 leaves 1, and only the lone number can supply it, so bit 1 of the answer is 1.
bit 0bit 1nums201201311201count14ans11=3answer: 3
return3
The kept bits read 11, which is 3. Every higher column has count 0, so nothing changes there, and bit 31 is 0, so no sign fix is needed. The repeated values never had to be found or removed: their 1s simply came in groups of 3.
05

Two bitmasks: ones and twos

For each bit position, ones and twos together hold how many times a 1 has been seen there, after dividing by 3: neither set means 0, ones set means 1, twos set means 2.

  • ones = (ones ^ n) & ~twos: a new 1 flips the bit into ones, unless that position is already at 2.
  • twos = (twos ^ n) & ~ones: a position at 1 that sees another 1 has just left ones, so it moves into twos; a position at 2 that sees a third 1 clears, because ones stayed 0 there.

After all numbers, a tripled value has cycled every one of its bits back to 0, so ones holds exactly the lone number.

▶1class Solution:
▶2 def singleNumber(self, nums):
▶3 ones = twos = 0
▶4 for n in nums:
▶5 ones = (ones ^ n) & ~twos
▶6 twos = (twos ^ n) & ~ones
▶7 return ones
06

Common pitfalls

Shifting a signed 1 into bit 31 in C++

✗ Wrong
int ans = 0;
...
if (count % 3) ans |= 1 << i;
✓ Right
unsigned ans = 0;
...
if (count % 3) ans |= 1u << i;
return (int)ans;

For [1, 1, 1, -3] the lone number has bit 31 set, so the loop runs 1 << 31. On a signed int that shift does not fit; LeetCode's sanitizer stops it with a runtime error. Building the answer in an unsigned and casting once at the end avoids it. Java defines this shift, so its int code is fine.

Using the sum formula from some tutorials

✗ Wrong
return (3 * sum(set(nums)) - sum(nums)) // 2
✓ Right
count the bits in each of the 32 positions

Three times the sum of the distinct values, minus the full sum, is twice the lone number, so the formula gives the right answer. But the set takes O(n) memory, which the problem forbids, and in Java or C++ the sums overflow int: for [2147483647, 2147483647, 2147483647, 5] the value 3 * (2147483647 + 5) does not fit.

07

Edge cases

The lone number is 0

For [4, 4, 4, 0] every column holds 0 or 3 ones, so no bit is ever set and ans stays 0, which is correct.

A single element

For [6] each count is just that number's own bit, 0 or 1, so the loop copies the number bit by bit.

08

Complexity

Time
O(n)
Space
O(1)
The outer loop runs 32 times and each pass reads all n numbers, so the work is 32 · n, which is linear. Only ans, count and the loop variables are stored.
09

Single Number II FAQ

What if every other number appears k times instead of 3?

Replace % 3 with % k. Each column count is then a multiple of k except where the lone number has a 1, so the same 32-position loop works for any k of 2 or more. The two-mask trick does not carry over as easily: it needs a different set of masks for each k.

What if the lone number appears twice instead of once?

The same code still works. Where that number has a 1, the column count leaves a remainder of 2 instead of 1, and if count % 3: treats any non-zero remainder as a set bit.

Can I just sort the array?

Sorting puts the three copies of each value next to each other, so you can step through in groups of 3 and return the first value whose group breaks. It is correct, but sorting takes O(n log n) time, which misses the linear-time requirement.