loading

Single Number — Step-by-Step Visualization

easyLeetCode #136ArrayBit Manipulation

Given a non-empty array of integers `nums`, every element appears twice except for one. Find that single one. You must implement a solution with a linear runtime complexity and use only constant extra space.

Algorithm Pattern

Bit Manipulation (XOR)

Key Idea

The XOR operation has two key properties: (1) `x ^ x = 0` (any number XORed with itself is 0) and (2) `x ^ 0 = x` (any number XORed with 0 is itself). By XORing all numbers in the array together, all pairs will cancel each other out to 0, leaving only the single unique number.

Step-by-Step Approach

  1. Initialize `res = 0`.
  2. Iterate through the array `nums`.
  3. For each element, update `res = res ^ num`.
  4. Return `res`.

Common Gotchas

  • This only works if every other number appears exactly an even number of times.
  • Wait, why is it constant space? Because we only use one integer variable `res` regardless of the array size.

Related Problems