TRT
Sign in
easyFoundationsLeetCode#xor

Single number

Every value in an array appears twice except one. Find it in linear time and constant extra memory.

The Runtime Theory Team1 min read
Taught inBits, bytes and number representationEvery value a program stores is a row of bits. How integers are laid out in bytes, how negative numbers work, and why adding 1 can turn a huge number negative.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [2, 2, 1]

out1

innums = [4, 1, 2, 1, 2]

out4

innums = [1]

out1

Given a non-empty array of integers in which every element appears exactly twice except for one, return the element that appears once. Use O(n) time and O(1) extra space.

Before you code

A hash set solves it in O(n) time but O(n) space. The constant-space answer works on the bits directly: there is an operation that cancels a value when it is applied twice.

Hints

  1. XOR (^) sets each bit of the result where the two inputs differ. So x ^ x is 0 and x ^ 0 is x.
  2. XOR is commutative and associative, so the order of the elements doesn't matter.
  3. XOR every element together. Each pair cancels to 0, and what remains is the single number. Negative numbers work too, because XOR acts on the two's-complement bits.

Production & complexity notes

When solving Single number on LeetCode (easy), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Bits, bytes and number representation to reinforce the underlying pattern.

What it practices

Treating integers as bit patterns, from Bits, bytes and number representation.

Not started

Sign in to save your learning progress.

Sign in to save