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.
- 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.
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.
"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.
Approach
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.
Two ways to solve it
Count the ones in each of the 32 bit positions and keep the remainder after dividing by 3.
- Easy to explain: each step follows from the counting argument.
- Works for any k: change
% 3to% k.
The answer most interviewers expect first.
Keep two masks that count every bit position at once, cycling 0 → 1 → 2 → 0.
- One pass: no 32-step outer loop.
- No sign fix: works on negatives in every language.
Pick it as the follow-up when asked for one pass.
Both use O(1) space. Counting per position is easier to derive and to adapt; the two-mask version does the same counting for all 32 positions in parallel, about 32 times fewer steps. The steps, code and live demo follow the bit count, and the two-mask code comes after the demo.
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.
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.
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.
Code in Python, C++ and Java
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 intoones, unless that position is already at 2.twos = (twos ^ n) & ~ones: a position at 1 that sees another 1 has just leftones, so it moves intotwos; a position at 2 that sees a third 1 clears, becauseonesstayed 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.
Common pitfalls
Shifting a signed 1 into bit 31 in C++
int ans = 0; ... if (count % 3) ans |= 1 << i;
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
return (3 * sum(set(nums)) - sum(nums)) // 2
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.
Edge cases
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.
For [6] each count is just that number's own bit, 0 or 1, so the loop copies the number bit by bit.
Complexity
ans, count and the loop variables are stored.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.