Bit manipulation / Beginner
Single Number with XOR Visualizer
XOR is 1 where two bits differ. x ^ x = 0 and x ^ 0 = x, and the order does not matter. So XOR everything: each pair cancels itself, and only the single value is left.
Start the Single Number with XOR simulation → Step forward and back, change the input, follow the code line by line in Java, Python, C++, C or JavaScript. Free, no sign-up.
Time and space complexity
| Best time | O(n) |
|---|---|
| Average time | O(n) |
| Worst time | O(n) |
| Extra space | O(1) |
Worked example, step by step
The same steps the simulator shows, on a small input.
- acc starts at 0.
- Value 1: x = 4. XOR flips every bit of acc where x has a 1.
- acc is now 4.
- Value 2: x = 1. XOR flips every bit of acc where x has a 1.
- acc is now 5.
- Value 3: x = 2. XOR flips every bit of acc where x has a 1.
- acc is now 7.
- Value 4: x = 1. XOR flips every bit of acc where x has a 1.
- acc is now 6.
- Value 5: x = 2. XOR flips every bit of acc where x has a 1.
- acc is now 4.
- Every pair cancelled out. The value that appears once is 4.
Single number with XOR in Java, Python, C++, C and JavaScript
int singleNumber(int[] nums) {
int acc = 0;
for (int x : nums) {
acc ^= x;
}
return acc;
}
def single_number(nums):
acc = 0
for x in nums:
acc ^= x
return acc
int singleNumber(const vector<int>& nums) {
int acc = 0;
for (int x : nums) {
acc ^= x;
}
return acc;
}
int singleNumber(int nums[], int n) {
int acc = 0;
for (int i = 0; i < n; i++) {
acc ^= nums[i];
}
return acc;
}
function singleNumber(nums) {
let acc = 0;
for (const x of nums) {
acc ^= x;
}
return acc;
}In an interview
LeetCode 136, Single Number. Related: 268 Missing Number, 137 Single Number II, 260 Single Number III.
A HashSet works in O(n) space; sorting works in O(n log n). XOR does it in one pass and O(1) space, which is the answer interviewers are looking for.