InterviewPrepKit

Home / Coding / Bit Manipulation

Single Number

easy Original ↗
Solving tips
  • XOR fold is the canonical tool: XOR every element together, paired values cancel (x^x=0) and the loner survives (x^0=x).
  • Seed the accumulator with 0 (XOR's identity); one pass, one variable, O(n) time and O(1) space, satisfying the constant-space requirement a hash set would violate.
  • XOR is commutative and associative, so scattered duplicates cancel regardless of order.
  • Caveat: this only works when the odd one appears once and all others an even number of times; 'appears three times' (Single Number II) needs mod-3 bit counting instead.

Problem

You are given a non-empty array nums in which every element appears exactly twice except for one element, which appears exactly once. Return that single element. You must do it in linear time using only constant extra space.

Examples

  • [2, 2, 1]1 — the two 2s pair up; 1 is alone.
  • [4, 1, 2, 1, 2]4 — the 1s and 2s each pair up; 4 is alone.
  • [7]7 — a single element with no partner.

Constraints

  • 1 <= len(nums) <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
  • Every element appears twice except one, which appears once.

Required: O(n) time and O(1) extra space.

Think about it first

Hint 1 A hash map of counts, or a set you toggle membership in, finds the loner — but both use O(n) extra space, which the problem forbids.
Hint 2 XOR has two magic properties: `x ^ x = 0` (a value cancels itself) and `x ^ 0 = x` (zero is the identity). And XOR doesn't care about order.
Hint 3 XOR every element of the array together. Each paired value cancels to `0`, and the lone value XORed with `0` is itself — so the running XOR *is* the answer, in one pass with a single variable.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.