The problem
You get a non-empty array of integers. Every value appears exactly twice, except one value that appears once. Return that value. The follow-up asks for O(n) time and O(1) extra space.
Input: [4, 1, 2, 1, 2]
Output: 41 and 2 each appear twice; 4 appears once.
How to think about it
Start with brute force. For each element, count how many times it appears by scanning the array: O(n²). A hash map of counts fixes the time to O(n), but uses O(n) space. Sorting and checking neighbours is O(n log n). None of these meets O(n) time with O(1) space.
The key insight: XOR cancels pairs. Three facts about XOR do all the work:
x ^ x = 0(a number cancels itself),x ^ 0 = x(zero changes nothing),- XOR is commutative and associative, so order does not matter.
So XOR-ing the whole array is the same as grouping each pair together: every pair becomes 0, and what is left is 0 ^ single = single. One pass, one variable.
Why it works bit by bit. Look at any single bit position. Each paired number contributes its bit twice, which cancels. Only the single number’s bit survives. XOR is “addition mod 2” per bit.
Which pattern is this? Bit manipulation, XOR cancellation. The tell is “every element appears twice except one”, especially with an O(1) space demand.
Approach
- Set
r = 0. - For every
xin the array, dor ^= x. - Return
r.
Solution
def single_number(nums):
r = 0
for x in nums:
r ^= x # pairs cancel: x ^ x = 0
return r
# single_number([4,1,2,1,2]) -> 4Dry run
On [4, 1, 2, 1, 2], with r shown in binary:
x |
r after r ^= x |
r (decimal) |
|---|---|---|
| 4 | 100 |
4 |
| 1 | 101 |
5 |
| 2 | 111 |
7 |
| 1 | 110 |
6 |
| 2 | 100 |
4 |
The 1s and 2s switch their bits on and then off again. The answer is 4.
Complexity
- Time: O(n). One pass, one XOR per element.
- Space: O(1). Only the running value
r.
Edge cases and pitfalls
- Single-element array (
[1]) returns that element. - Negative numbers work in Python: XOR uses two’s-complement bits on unbounded ints, so
[-3, 5, 5]returns-3. - Starting
rat the first element instead of 0 works too, but 0 is cleaner and handles every length. - If an element can appear three times, XOR fails. That is Single Number II.
Related problems
- Single Number II (LeetCode 137): every other number appears three times.
- Single Number III (LeetCode 260): two numbers appear once; XOR, then split.
- Missing Number (LeetCode 268): the same cancellation, between indices and values.
- 1.Single Number (LeetCode 136)
- 2.Number of 1 Bits (LeetCode 191)
- 3.Counting Bits (LeetCode 338)
- 4.Reverse Bits (LeetCode 190)
- 5.Missing Number (LeetCode 268)
- 6.Single Number II (LeetCode 137)
- 7.Single Number III (LeetCode 260)
- 8.Sum of Two Integers (LeetCode 371)
- 9.Bitwise AND of Numbers Range (LeetCode 201)
- 10.Subsets (bitmask enumeration) (LeetCode 78)