LeetCode #136 Easy

Single Number

Single Number is LeetCode 136 (Easy). You are given a non-empty integer array nums. Every element appears exactly twice except one, which appears once. Return that single element.

  • The solution must run in linear time and use only constant extra space. That rules out a hash set and sorting.
  • Values can be negative, from -3 × 10⁴ to 3 × 10⁴.
Constraints
  • 1 <= nums.length <= 3 * 10⁴
  • -3 * 10⁴ <= nums[i] <= 3 * 10⁴
  • Each element appears twice except for one element which appears only once
bit-manipulationarrayxor
Open on LeetCode ↗
02

Intuition

XOR (^) compares two numbers bit by bit: a result bit is 1 when the two bits differ, and 0 when they match. Two rules follow:

  • A number cancels itself: x ^ x = 0, because every bit matches itself.
  • Zero changes nothing: x ^ 0 = x.

XOR also ignores order: a ^ b ^ a equals a ^ a ^ b. So XOR-ing the whole array gives the same result as pairing up equal numbers first. Each pair becomes 0, and the single number is all that is left.

How to spot this pattern

Reach for XOR when every value has a partner except one, or when two lists differ by one element: Missing Number (LeetCode 268) and Find the Difference (LeetCode 389) use the same cancelling. If the other numbers appear three times, XOR no longer cancels them; see Single Number II. With two unpaired numbers, see Single Number III.

03

Approach

Try it first

Before reading on: write 5 and 3 in binary and compute 5 ^ 3 ^ 5 bit by bit. Would the result change if the two 5s were next to each other?

1

Start the answer at 0

Set ans = 0. Because x ^ 0 = x, the start value adds nothing, so a one-element array returns that element with no special case.

2

XOR every element into the answer

For each n in nums, do ans ^= n. You never need to find the pairs: the first copy of a number flips some bits of ans, and the second copy flips the same bits back, wherever it sits in the array.

3

Return the answer

After the loop, every number that appears twice has cancelled out, so ans holds the single number. One pass and one variable: O(n) time, O(1) space, exactly what the problem asks for.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def singleNumber(self, nums: List[int]) -> int:
▶3 ans = 0
▶4 for n in nums:
▶5 ans ^= n
▶6 return ans
nums4011221324bits421ans000=0ans = 0
ans0XOR with 0 changes nothing
Start the answer at 0. XOR with 0 leaves any number unchanged, so 0 is a safe empty start: after one element, ans is exactly that element.
nums4011221324bits421ans000=0num^100=4new ans100=40 xor 4 = 4
num4nums[0]
ans40 ^ 4
XOR in 4. Each bit of the result is 1 where exactly one of the two rows has a 1. The highlighted bits are the ones 4 flipped.
nums4011221324bits421ans100=4num^001=1new ans101=54 xor 1 = 5
num1nums[1]
ans54 ^ 1
XOR in 1. Each bit of the result is 1 where exactly one of the two rows has a 1. The highlighted bits are the ones 1 flipped. Its pair, if it has one, will flip them back later.
nums4011221324bits421ans101=5num^010=2new ans111=75 xor 2 = 7
num2nums[2]
ans75 ^ 2
XOR in 2. Each bit of the result is 1 where exactly one of the two rows has a 1. The highlighted bits are the ones 2 flipped. Its pair, if it has one, will flip them back later.
nums4011221324bits421ans111=7num^001=1new ans110=67 xor 1 = 6 · the two 1s cancel
num1nums[3]
ans67 ^ 1
XOR in the second 1. Every bit it turned on the first time is turned off again, so the pair adds nothing: 1 ^ 1 = 0. The order did not matter; the copies did not need to be next to each other.
nums4011221324bits421ans110=6num^010=2new ans100=46 xor 2 = 4 · the two 2s cancel
num2nums[4]
ans46 ^ 2
XOR in the second 2. Every bit it turned on the first time is turned off again, so the pair adds nothing: 2 ^ 2 = 0. The order did not matter; the copies did not need to be next to each other.
nums4011221324bits421ans100=4pairs cancelled → return 4
return4
Every number that appears twice has cancelled itself, so only the one without a partner is left in ans: 4. One pass, one variable.
05

Common pitfalls

Using a hash set to find the single number

✗ Wrong
seen = set()
for n in nums:
    if n in seen:
        seen.remove(n)
    else:
        seen.add(n)
✓ Right
ans = 0
for n in nums:
    ans ^= n

It gives the right answer, but the set can hold about n / 2 numbers, which breaks the O(1) extra space rule. The XOR answer keeps the same "seen an odd number of times" information in one integer.

Starting at nums[0] and still looping over every element

✗ Wrong
ans = nums[0]
for n in nums:
    ans ^= n
✓ Right
ans = 0
for n in nums:
    ans ^= n

The first element is XOR-ed in twice and cancels itself, so the result is wrong whenever the single number is nums[0]. Start at 0, or start at nums[0] and loop from index 1.

Using XOR when the others appear three times

✗ Wrong
ans ^= n  # every other number appears 3 times
✓ Right
# count each bit's ones modulo 3 (Single Number II)

XOR only cancels pairs. A number seen three times leaves one copy behind and mixes into the answer, so that variant needs a different trick.

06

Edge cases

Negative numbers, e.g. [-1, 2, 2]

XOR works on the stored bit pattern, sign bit included, so -1 ^ -1 is still 0 and the answer is -1. No special handling is needed.

07

Complexity

Time
O(n)
Space
O(1)
One pass over the array with a single integer. A hash set would also be O(n) time but O(n) space.
08

Single Number I, II and III

The three problems sound alike but need different tricks.

Single Number (136)Single Number II (137)Single Number III (260)
Other numbers appeartwicethree timestwice
Numbers to returnoneonetwo
TrickXOR everythingcount each bit modulo 3XOR everything, then split by one differing bit
Time, spaceO(n), O(1)O(32 n), O(1)O(n), O(1)
09

Single Number FAQ

How do you solve this problem?
  • Start: ans = 0.
  • Fold: XOR every element into ans; each pair cancels to 0.
  • Answer: return ans, the only number without a partner.
  • Complexity: O(n) time, O(1) extra space.
Can you solve it with a hash set or by sorting?

Yes, but each breaks one rule. A hash set (add on first sight, remove on second) is O(n) time and O(n) space. Sorting puts equal numbers next to each other so you can check pairs, which is O(n log n) time. Only the XOR solution meets both O(n) time and O(1) space.

Is there a one-line Python solution?

Yes: return functools.reduce(operator.xor, nums). It does the same fold as the loop, starting from the first element instead of 0, which gives the same result.