Skip to content

Single Number

Find the one number that appears once when every other number appears twice, using XOR and O(1) space.

EasyBit Manipulation
Solve on LeetCode

The problem

You get a non-empty integer array nums in which every value appears exactly twice, except for one value that appears once. Return that value, using linear time and only constant extra space.

Input nums = [7, 3, 5, 3, 7]

Output 5

The 7s and the 3s come in pairs, and 5 is alone.

Input nums = [-6, 4, 4]

Output -6

Negative numbers work the same way.

Key constraint: Only O(1) extra space is allowed, which rules out a hash map or a set of numbers seen so far.

How to spot the pattern

  • Everything comes in pairs except one item.
  • You must use constant extra space, so you can't remember what you have seen.

The idea

XOR has two handy rules: x ^ x = 0 and x ^ 0 = x, and the order of the XORs doesn't matter. So if you XOR all the numbers together, every pair cancels to 0 wherever its two copies sit, and what is left is the number without a partner.

Brute force: Count each value in a hash map and return the one seen once, which takes O(n) time but also O(n) extra space.

Step by step

  1. 1Start with result = 0.
  2. 2XOR every number into result.
  3. 3Return result, since every pair has cancelled out.

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        result = 0
        for x in nums:
            result ^= x  # x ^ x = 0, so every pair cancels out
        return result

Complexity

Time

O(n)

Space

O(1)

One pass that keeps a single number.

Watch out for

  • Reaching for a hash map or for sorting: both find the answer, but break the O(1) space or the O(n) time rule.
  • Expecting XOR to fail on negative numbers: it works bit by bit on their two's complement form, so they cancel like any other pair.

Follow-up questions

What if every other number appears three times?

For each of the 32 bit positions, count how many numbers have that bit set. The positions where the count is not a multiple of 3 are the bits of the single number. That is Single Number II.

What if two numbers appear once?

XOR everything to get a ^ b, pick any 1 bit of it, and split the numbers by that bit; XOR each group on its own to get a and b. That is Single Number III.

In Hinglish

XOR mein same number do baar aaye toh 0 ho jaata hai. Saare numbers ka XOR le lo, jodi wale cancel ho jayenge aur akela number bach jayega.

Related problems