CodeArchon

easyBit ManipulationMicrosoft

Missing Spot Finder

A librarian has shelf slots 0..n but one is empty; find the missing slot number.

Given an array of n distinct numbers in [0, n], return the missing one.

Choose approach

3
0
0
1
1
2
Mapstate
x→3
1/5
Narrationstep 1 of 5

Seed x = n = 3.

1def missingNumber(nums):
2 x = len(nums)
3 for i, v in enumerate(nums): x ^= i ^ v
4 return x
Variables
x=3

How to think about it

  1. Sum formula also works (n(n+1)/2 - sum(nums)).
  2. XOR avoids overflow.

Edge cases to catch in interview

  • Missing 0.
  • Missing n.

Examples

Example 12
{"values":[0,1]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed