Single Number
Every input value occurs twice except one value that occurs once. Return the unpaired value.
Every input value occurs twice except one value that occurs once. Return the unpaired value.
Input and constraints
- Exactly one value occurs once and every other value occurs twice.
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): result = 0 i = 0 while (i < len(values)): result = (result ^ values[i]) i = (i + 1) return resultVisualizer
Step 1 of 6Inspect the current state
Toggle the value at position 0 into the running XOR.
Variable watch
Step explanation
Toggle the value at position 0 into the running XOR.
Worked explanation
Paired light switches toggle a lamp twice, restoring its original state.
Guided solution
Equal numbers cancel under XOR. Rearranging pairs cannot change the result.
O(n) time · O(1) auxiliary space
Examples
Worked example · {"values":[6,2,6,-3,2],"target":0} ⇒ -3
Edge case 1 · {"values":[0],"target":0} ⇒ 0
Edge case 2 · {"values":[-1,0,0],"target":0} ⇒ -1
Progressive hints
Hint 1
Paired light switches toggle a lamp twice, restoring its original state.Hint 2
Equal numbers cancel under XOR. Rearranging pairs cannot change the result.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
This cancellation does not isolate a single value when repeated numbers occur three times.
Interview follow-up
How would you isolate two different unpaired numbers?