Try it first — give it 25 minutes
0/4 revealedStuck? Take one hint at a time. The struggle is where the pattern sticks.
The problem in plain English
You get an array nums. Every value appears exactly three times, except one value that appears exactly once. Return that value.
As in Single Number, you must use O(n) time and O(1) extra space. Values can be anything in the 32-bit signed range, from −2³¹ to 2³¹ − 1, so negatives matter.
Example: nums = [0, 1, 0, 1, 0, 1, 99] → 99.
Start with brute force
A hash map of counts finds the value with count 1 in O(n) time, but uses O(n) space. Sorting and scanning in groups of three uses O(1) extra space but O(n log n) time. Neither meets both limits.
The Single Number trick fails too. XOR cancels pairs, but x ^ x ^ x = x. Three copies leave a copy behind, so XOR-ing everything gives the loner XOR-ed with every tripled number: garbage.
Building the intuition
XOR worked because, in each bit column, it kept a count modulo 2. Pairs added 0 or 2 to a column, and modulo 2 that disappears.
So generalise: keep a count modulo 3 in each column.
Write [2, 2, 3, 2] in binary and stack the numbers up:
bit1 bit0
2 = 1 0
2 = 1 0
3 = 1 1
2 = 1 0
sum 4 1
sum % 3 1 1 → binary 11 = 3Each number appearing three times adds either 0 (bit off) or 3 (bit on) to a column. Modulo 3, its contribution vanishes. What's left in each column is the single number's bit. Column 1: 4 % 3 = 1. Column 0: 1 % 3 = 1. Reading 11 gives 3, which is the answer.
There are only 32 columns, so this is 32 passes over the array. That's 32n steps, which is still O(n), and we only need a counter and the result, which is O(1) space.
The optimal approach
result = 0.- For each
bitfrom 0 to 31:- count how many numbers have that bit set: add
(x >> bit) & 1for everyx; - if
count % 3 != 0, set that bit in the result:result |= 1 << bit.
- count how many numbers have that bit set: add
- Return
result, read as a signed 32-bit integer.
The subtle detail is negative numbers, because the single number might be negative, which means bit 31 is set (two's complement).
- Java and JavaScript: setting bit 31 of a 32-bit signed integer makes it negative automatically. Nothing extra to do.
- C++: use
uint32_tfor the shifting so it's a plain bit pattern, then cast tointat the end. - Python: ints have no fixed width, so
1 << 31is just the positive number 2,147,483,648. Ifresult ≥ 2³¹, subtract 2³² to get the negative value those 32 bits mean. Reading bits out of a negative Python int works fine: Python acts as if negatives have infinitely many leading 1s, so(x >> bit) & 1gives the right two's complement bit.
The code
Every solution below is tested against the examples and edge cases before it ships. Pick your language — we'll remember it.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
result = 0
for bit in range(32):
# Every number that appears three times adds 0 or 3 to this column,
# so whatever is left after % 3 is the single number's bit
count = 0
for x in nums:
count += (x >> bit) & 1
if count % 3:
result |= 1 << bit
# Python ints have no 32-bit limit, so bit 31 reads as +2^31.
# In two's complement it means -2^31: shift the value down by 2^32.
if result >= 1 << 31:
result -= 1 << 32
return resultclass Solution {
public:
int singleNumber(vector<int>& nums) {
uint32_t result = 0;
for (int bit = 0; bit < 32; bit++) {
// Every number that appears three times adds 0 or 3 to this column,
// so whatever is left after % 3 is the single number's bit
int count = 0;
for (int x : nums) {
count += ((uint32_t)x >> bit) & 1; // unsigned: plain bit pattern, no sign tricks
}
if (count % 3 != 0) {
result |= 1u << bit;
}
}
return (int)result; // the 32 bits already are the two's complement answer
}
};class Solution {
public int singleNumber(int[] nums) {
int result = 0;
for (int bit = 0; bit < 32; bit++) {
// Every number that appears three times adds 0 or 3 to this column,
// so whatever is left after % 3 is the single number's bit
int count = 0;
for (int x : nums) {
count += (x >> bit) & 1;
}
if (count % 3 != 0) {
result |= 1 << bit; // setting bit 31 makes result negative, exactly as it should
}
}
return result;
}
}/**
* @param {number[]} nums
* @return {number}
*/
var singleNumber = function (nums) {
let result = 0;
for (let bit = 0; bit < 32; bit++) {
// Every number that appears three times adds 0 or 3 to this column,
// so whatever is left after % 3 is the single number's bit
let count = 0;
for (const x of nums) {
count += (x >> bit) & 1;
}
if (count % 3 !== 0) {
result |= 1 << bit; // JS bitwise ops are signed 32-bit, so bit 31 makes it negative
}
}
return result;
};Dry run
nums = [-2, -2, 1, 1, 4, 1, 4, 4, -4, -2]. The answer should be -4. In 32-bit two's complement, -2 is 111…1110, -4 is 111…1100, 1 is …0001 and 4 is …0100.
| bit | which numbers have it | count | count % 3 | result bit |
|---|---|---|---|---|
| 0 | the three 1s | 3 | 0 | 0 |
| 1 | the three −2s | 3 | 0 | 0 |
| 2 | three −2s, three 4s, one −4 | 7 | 1 | 1 |
| 3 … 31 | three −2s and one −4 | 4 | 1 | 1 |
The result is bits 2 to 31 set and bits 0 and 1 clear: 111…1100, which is -4. In Python that pattern first comes out as 4,294,967,292; subtracting 2³² gives -4.
Complexity
- Time: O(n). Exactly 32 passes of n steps. The 32 is a constant that doesn't grow with the input.
- Space: O(1). A counter and the result.
Edge cases and traps
- Python returning a huge positive number. If you forget the sign fix-up, a negative answer like
-4comes back as4294967292. - Looping only 31 bits. Bit 31 is the sign bit. Skip it and every negative answer is wrong.
- C++ shifting a negative
intleft into the sign bit. Do the bit-building inuint32_t. INT_MINas the loner.[5, -2147483648, 5, 5]has only bit 31 set in the answer. Java and JS handle it; Python must subtract 2³².- Single element
[x]. Every column count is 0 or 1, so you rebuildxexactly.
Say it in the interview
"XOR doesn't work, because three copies XOR to the number itself. Instead I look at each of the 32 bit positions separately. Every number that appears three times adds 0 or 3 to that position's count, so count mod 3 is the single number's bit. I rebuild the answer bit by bit. That's 32 passes, so O(n) time, with constant space. I need to treat bit 31 as the sign bit, which in Python means subtracting 2 to the 32 if it's set."
Follow-ups interviewers ask
- "Can you do it in one pass?" Yes: keep two masks,
onesandtwos, which together act as a 2-bit counter per column that resets at 3. For eachx:ones = (ones ^ x) & ~twos, thentwos = (twos ^ x) & ~ones. At the end,onesis the answer. Same complexity, fewer passes, but much harder to derive under pressure. - "What if every other number appears k times?" The same bit-counting works with
count % k. - "Why not just sum?"
3 × sum(set(nums)) − sum(nums) = 2 × lonerworks, but building the set costs O(n) space.
Practise the same idea
This is a bonus day of the free DSA plan 🐸
90 problems in the order that builds on itself, one a day, with a walkthrough like this for each. Tick them off and keep your streak.
Get the full roadmap — free