Single Number

EasyBit Manipulation · XOR🧩 Bit ManipulationLeetCode #136 ↗Updated

Problem

In a non-empty integer array nums, every value occurs exactly twice except one value that occurs once. Return that lonely value, ideally in linear time with constant extra memory.
Input[2,2,1]Output1
Input[4,1,2,1,2]Output4
Input[1]Output1

1 ≤ n ≤ 3·104  ·  -3·104 ≤ nums[i] ≤ 3·104  ·  Required: O(n) time, O(1) extra space.

Try it yourself

Java
class Solution {
    public int singleNumber(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
XOR is a cancel-out operator: x ^ x = 0, x ^ 0 = x, and order doesn't matter. XOR everything and all pairs vanish, leaving the single value.
PatternBit Manipulation

Instinct Pairs that cancel, counting 1s, powers of two, subsets as numbers, or 'no + or - allowed' - drop to binary and use XOR, AND, OR and shifts.

Memory hack XOR is a forgetful twin detector - see something twice and it vanishes; n & (n-1) snips off the last lit bulb.

Open the Bit Manipulation guide →

Approaches

Brute ForceCheck Every Element Against All

Time O(n2)Space O(1)

For each index i, scan the whole array for another index with the same value. The first element with no partner is the answer.

Java
public int singleNumber(int[] nums) {
    for (int i = 0; i < nums.length; i++) {
        boolean isSingle = true;
        for (int j = 0; j < nums.length; j++) {
            if (i != j && nums[i] == nums[j]) {
                isSingle = false; // found its pair
                break;
            }
        }
        if (isSingle) return nums[i];
    }
    return -1; // unreachable for valid input
}

No extra memory, but quadratic — too slow for n = 3·104 in the worst case.

At a glance

LevelApproachTimeSpace
Brute ForceCheck Every Element Against AllO(n2)O(1)
BetterHash Map Frequency CountO(n)O(n)
OptimalXOR All ElementsO(n)O(1)
Common pitfalls
  • Using sum tricks (2·sum(set) - sum) — needs O(n) space and can overflow.
  • Starting the XOR accumulator at anything other than 0.
  • Assuming non-negative values — XOR works fine on negatives (two’s complement).
Interview tips
  • State the three XOR laws out loud: self-inverse, identity 0, commutative.
  • Mention sorting (O(n log n), O(1)) as a middle ground if asked.
  • Expect follow-ups: Single Number II (thrice) and III (two singles).
Pattern
XOR cancellation → find the odd-one-out when everything else appears an even number of times.
My notes saved in this browser