Missing Number
The input has distinct values from zero through n inclusive, with one number missing. Identify that number.
The input has distinct values from zero through n inclusive, with one number missing. Identify that number.
Input and constraints
- Use distinct values from 0 through n inclusive.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): result = len(values) i = 0 while (i < len(values)): result = ((result ^ i) ^ values[i]) i = (i + 1) return resultVisualizer
Step 1 of 4Inspect the current state
Cancel the expected index and supplied value together.
Variable watch
Step explanation
Cancel the expected index and supplied value together.
Worked explanation
Pair expected roll-call cards with attended cards; the unmatched card remains.
Guided solution
XOR every expected number and every supplied number. All values present in both groups cancel.
O(n) time · O(1) auxiliary space
Examples
Worked example · {"values":[3,0,1],"target":0} ⇒ 2
Edge case 1 · {"values":[],"target":0} ⇒ 0
Edge case 2 · {"values":[0],"target":0} ⇒ 1
Progressive hints
Hint 1
Pair expected roll-call cards with attended cards; the unmatched card remains.Hint 2
XOR every expected number and every supplied number. All values present in both groups cancel.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
The inclusive upper endpoint n also belongs to the expected set.
Interview follow-up
Would an arithmetic sum also work for this bounded input?