Single Number
Given an array where every element appears twice except one, find the single element. Must run in O(n) time and O(1) space.
Example
2,2,1
1
numsholds the values , so . The promise is that every value occurs exactly twice except one value that occurs once, so is always odd: , here .- Counting occurrences: the value sits at positions and (count ); the value sits at position (count ).
- The answer is the one value whose count is odd, here , so the output is
1. - The output is a single integer taken from the array itself, not an index or a count. Order is irrelevant: the arrangements 1, 2, 2 or 2, 1, 2 give the same answer.
- Notice the limits: time means each element is looked at a constant number of times, and space means the extra memory cannot grow with , so a separate tally for every distinct value is off the table. Values can be negative (down to ), and a one-element array such as just returns its element.
Constraints
- 1 <= len(nums) <= 3 * 10^4
- -3 * 10^4 <= nums[i] <= 3 * 10^4