Single Number (LeetCode 136): Solution and Explanation

Easy
Array
Bit Manipulation

Every value in a non-empty array appears exactly twice, except for one value that appears only once. Find that lonely value in linear time while using only a constant amount of extra memory.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Without the memory limit, a hash map of counts or a set that adds and removes values solves this in one pass. Sorting also works, since pairs end up next to each other. But the hash approaches use O(n) space and sorting costs O(n log n), so neither meets both requirements.

Another idea is arithmetic: twice the sum of the distinct values minus the sum of the array gives the single value. That still needs a set to find the distinct values. What you really want is an operation that, applied across the whole array, makes each pair erase itself and leaves the single value standing.

Bitwise XOR is exactly that operation. It has three properties that matter here: a ^ a = 0, a ^ 0 = a, and it is both commutative and associative, so the order in which you combine values does not matter. If you XOR every number together, you can mentally regroup the expression so that each pair sits side by side, each pair collapses to 0, and the zeros vanish, leaving only the value without a partner.

At the bit level the picture is just as clear. XOR acts as a parity counter for each bit position. A bit contributed by a paired value is flipped an even number of times and ends at 0, while the bits of the single value are flipped one extra time and survive. The result is one integer variable and one pass.

Approach: XOR accumulation

  1. Initialize result = 0, since XOR with 0 leaves a value unchanged.
  2. Loop over every number in nums.
  3. Update result ^= num, folding the number into the running XOR.
  4. Paired values cancel each other no matter where they appear in the array.
  5. After the loop, result holds the single value, so return it.

Step-by-step example

nums = [4,1,2,1,2]
  1. Start with result = 0, which is 000 in binary.
  2. XOR with 4 (100) gives 100, which is 4.
  3. XOR with 1 (001) gives 101, which is 5. XOR with 2 (010) gives 111, which is 7.
  4. XOR with 1 again clears the lowest bit, giving 110, which is 6.
  5. XOR with 2 again clears the middle bit, giving 100, which is 4.
  6. Both pairs have cancelled, so the answer is 4.

Code: Python, Java, C++

1class Solution:
2    def singleNumber(self, nums: List[int]) -> int:
3        result = 0
4        for num in nums:
5            result ^= num  # XOR cancels out duplicates
6        return result

Time and space complexity

Time

O(n)

The loop visits each element once and does a single XOR, which is a constant-time operation.

Space

O(1)

Only the integer result is stored, regardless of the input size.

Other approaches

Hash set toggling (time O(n), space O(n))

Add a number to a set the first time you see it and remove it the second time. Whatever is left in the set at the end is the answer. It is easy to explain and generalizes to other counting rules, but it needs linear extra memory.

Sort and scan pairs (time O(n log n), space O(1))

Sort the array and step through it two at a time. The first index where nums[i] != nums[i + 1], or the last element if none, is the single value. It uses no hash table but is slower and modifies the input.

Common mistakes

  • Starting result at the first element and then looping over the whole array, which XORs the first element twice and cancels it.
  • Worrying about negative numbers. XOR works bit by bit on two's complement integers, so negative values cancel just like positive ones.
  • Applying the same trick when elements appear three times. XOR only cancels even counts, so that variant needs per-bit counting modulo 3.
  • Using the sum trick 2 × sum(set(nums)) - sum(nums) and calling it constant space. The set still holds up to n / 2 values.

Frequently asked questions

Why does XOR find the single number?

XOR of a number with itself is 0, XOR with 0 changes nothing, and the order of XOR operations does not matter. So every pair cancels out, and the only value left in the running XOR is the one without a partner.

Can Single Number be solved without extra space?

Yes. The XOR approach keeps only one integer, so it uses O(1) extra space while still running in O(n) time.

Does the XOR trick work with negative numbers?

Yes. XOR operates on the bit patterns, and identical negative numbers have identical bits, so they cancel the same way positive numbers do.

How does Single Number change if values appear three times?

XOR no longer works, because three copies of a value leave its bits set. Instead, count how many numbers have each of the 32 bits set and take each count modulo 3. The bits with a remainder of 1 belong to the single value, which keeps the solution at O(n) time and O(1) space.