Magicsheet logo

Single Number

Easy
70.4%
Updated 6/1/2025

Single Number

What is this problem about?

The "Single Number" interview question is one of the most famous coding challenges. You are given a non-empty array of integers where every element appears twice except for one. You need to find that unique element. While this sounds simple, the challenge often includes a constraint to solve it in linear time O(n) and using only constant extra space O(1). This "Single Number coding problem" is a gateway to understanding low-level data manipulation.

Why is this asked in interviews?

This problem is asked by almost every major company, including Apple, Microsoft, and Google. It is a perfect test of whether a candidate knows their bitwise operations. It filters out those who only know high-level logic from those who understand how data is actually stored and manipulated in memory. It's a classic example of an "elegant" solution that beats a "brute force" one in both speed and memory usage.

Algorithmic pattern used

The "Bit Manipulation interview pattern" is the star here, specifically the XOR (exclusive OR) operation. XOR has three critical properties:

  1. x ^ x = 0 (An element XORed with itself is zero)
  2. x ^ 0 = x (An element XORed with zero is itself)
  3. XOR is commutative and associative. If you XOR every number in the array together, all the pairs will cancel each other out (becoming zero), leaving only the single unique number at the end.

Example explanation

Suppose we have the array [4, 1, 2, 1, 2].

  1. Initialize result = 0.
  2. result = 0 ^ 4 -> 4
  3. result = 4 ^ 1 -> 5 (binary 100 ^ 001 = 101)
  4. result = 5 ^ 2 -> 7 (binary 101 ^ 010 = 111)
  5. result = 7 ^ 1 -> 6 (binary 111 ^ 001 = 110)
  6. result = 6 ^ 2 -> 4 (binary 110 ^ 010 = 100) The result is 4. Notice how the 1s and 2s eventually canceled their contributions, leaving the 4.

Common mistakes candidates make

Many candidates instinctively reach for a Hash Map to count frequencies. While this works in O(n) time, it uses O(n) space, violating the constant space constraint often imposed in this "Single Number interview question". Another mistake is trying to sort the array first, which takes O(n log n) time. The XOR trick is the only way to satisfy both the time and space constraints simultaneously.

Interview preparation tip

Bit manipulation is a niche but powerful tool in a developer's arsenal. Learn the basic properties of AND, OR, XOR, and NOT. These operations are not only useful for specific interview puzzles but are also critical in fields like cryptography, graphics, and performance-critical systems programming.

Similar Questions