Single Number

Easy

Topics
ArrayBit Manipulation

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

nums221
76543210200000010200000010100000001xor00000001
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

nums41212
76543210400000100100000001200000010100000001200000010xor00000100
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

  1. Initialize x = 0.
  2. XOR every element into x.
  3. 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 4

Complexity

  • 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 out
Asked at Airbnb TCS
SensAI
Beta
Tap the mic to stop voice mode