Array techniquesAnimated
Missing Number Algorithm
Expected sum 0..n minus the actual sum (or XOR everything).
Time
O(n)
Extra space
O(1)
Use it for
One value missing from 0..n.
How it works
- The array holds n distinct numbers from 0 to n, so exactly one is missing.
- The numbers 0..n add up to n(n+1)/2.
- Subtract the actual sum of the array: the difference is the missing number.
- Constant extra memory and one pass.
Watch it run
Loading animation…