#268

Missing Number

Easy XOR

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

The array holds n distinct numbers taken from 0..n. Exactly one is missing; find it.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: numbers 0..n with one missing; which one?

Why this works: XOR all indexes 0..n with all values. Every number that is present shows up twice and cancels.

Example: nums = [3, 0, 1], n = 3

start x = 3^0^3 → 0, ^1^0 → 1, ^2^1 → 2answer 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Forgetting to include n itself in the XOR (the indexes only go to n - 1).