Single Number
Easy
Topics
Given a non-empty array nums where every element appears twice except one, find that single one. Do it with O(n) time and O(1) extra space.
Example 1
nums
XOR cancels equal pairs (
v ^ v = 0) and ignores order, so XORing everything leaves exactly the unpaired value — 1. The bit rows show the columns cancelling.Top row is the input; below it the binary expansion of each value and of their XOR.
Input: nums = [2,2,1] Output: 1
Example 2
nums
Input: nums = [4,1,2,1,2] Output: 4
Constraints
- 1 <= nums.length <= 3*10^4
- Each element appears twice except one.
Editorial — intuition, approach, complexity and pitfalls
Intuition
XOR has two properties that make this elegant: a ^ a = 0 (a value XORed with itself cancels) and a ^ 0 = a.
XOR-ing every element together cancels all the pairs, and the lone element is left standing.
Approach
- Initialize
x = 0. - XOR every element into
x. - The paired numbers cancel to 0; the unique number remains.
Walkthrough
nums = [4, 1, 2, 1, 2]
0 ^ 4 = 4
4 ^ 1 = 5
5 ^ 2 = 7
7 ^ 1 = 6
6 ^ 2 = 4 -> answer 4Complexity
- Time — O(n): one pass.
- Space — O(1): a single accumulator — beats the O(n) hash-set solution the problem hints against.
Common Pitfalls
- XOR, not OR. OR accumulates bits and never cancels, so it returns the union of every value's bits -- 3 where the answer is 1.
- Start the accumulator at 0, not
nums[0]. Seeding it with the first element counts that element twice, which cancels it out and returns 3 instead of 1. - This only works because every other value appears exactly twice. XOR is the right tool for pairs; triples need the bit-counting variant, and saying so is what separates knowing the trick from knowing why it holds.
Full Solution — all languages
class Solution:
def singleNumber(self, nums):
out = 0
for v in nums:
out ^= v
return outimport java.util.*;
class Solution {
public int singleNumber(int[] nums) {
int out = 0;
for (int v : nums) out ^= v;
return out;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: int singleNumber(vector<int>& nums) {
int out = 0;
for (int v : nums) out ^= v;
return out;
}
};/**
* @param {number[]} nums
* @return {number}
*/ var singleNumber = function(nums) {
let out = 0;
for (const v of nums) out ^= v;
return out;
};