Single Number II
Medium
Topics
Every element in nums appears exactly three times except for one, which appears once. Return that single element. O(n) time and O(1) extra space.
Example 1
Input: nums = [2,2,3,2] Output: 3
Example 2
Input: nums = [0,1,0,1,0,1,99] Output: 99
Constraints
- 1 <= nums.length <= 3*10^4
- Each element appears 3x except one which appears once.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Every value except one appears three times, so for each bit position the total count of ones is a multiple of three plus the contribution of the answer. Summing each bit independently and taking it modulo three recovers the answer — that is the version to describe first, because it is obviously correct and it generalises to any repeat count.
The shown solution is the two-variable form of the same idea: a pair of masks acting as a mod-three counter, one bit per position. ones holds the bits seen once so far, twos the bits seen twice, and a third sighting clears both. The order of the two updates matters, because the second reads the ones the first just produced.
Approach
- Start
onesandtwosat zero. - For each value, set
ones = (ones ^ x) & ~twos. - Then set
twos = (twos ^ x) & ~ones, using the freshly updatedones. - After the pass,
onesholds the value seen exactly once.
Dry Run
nums = [2,2,3,2]
x ones twos
2 0b10 0b0 first sighting of bit 1
2 0b0 0b10 second sighting moves it to twos
3 0b1 0b0 bit 0 is new; bit 1 reaches three and clears
2 0b11 0b0 hmm -- bit 1 is seen a fourth time, so the cycle restarts
answer 3
[0,1,0,1,0,1,99] -> 99
[-2,-2,1,-2] -> 1 negatives work tooComplexity
- Time — O(n): one pass, two bitwise updates per element.
- Space — O(1): two integers, which is what the problem demands.
- The bit-count-modulo-three variant is also O(n) time and O(1) space — 32 fixed counters — and is far easier to defend under questioning.
Common Pitfalls
- Swapping the two update lines.
twosmust be computed from the newones; reversing them breaks the mod-three cycle. - Reaching for a hash map of counts. Correct and O(n) time, but O(n) space, and the problem asks for constant extra space.
- XOR-ing everything, as in single number I. XOR cancels pairs, not triples, so it returns garbage here.
- Assuming the input is non-negative. In a fixed-width language the masks handle the sign bit like any other bit; in Python the arbitrary-precision
~still gives the right answer, verified on[-2,-2,1,-2]. - In the bit-counting variant, forgetting to sign-extend the reconstructed value. If bit 31 survives the modulo, the result is negative and must be interpreted as such rather than as a large positive.
- Presenting the two-mask form without deriving it. It is effectively unguessable, and an interviewer will ask where it comes from — the mod-three counter is the derivation.
Full Solution — all languages
class Solution:
def singleNumber(self, nums):
ones = twos = 0
for x in nums:
ones = (ones ^ x) & ~twos
twos = (twos ^ x) & ~ones
return onesimport java.util.*;
class Solution {
public int singleNumber(int[] nums) {
int ones = 0, twos = 0;
for (int x : nums) {
ones = (ones ^ x) & ~twos;
twos = (twos ^ x) & ~ones;
}
return ones;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int singleNumber(vector<int>& nums) {
int ones = 0, twos = 0;
for (int x : nums) {
ones = (ones ^ x) & ~twos;
twos = (twos ^ x) & ~ones;
}
return ones;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var singleNumber = function(nums) {
let ones = 0, twos = 0;
for (const x of nums) {
ones = (ones ^ x) & ~twos;
twos = (twos ^ x) & ~ones;
}
return ones;
};