Single Number
EasyNeetCode 150Top Interview 150 Bit ManipulationProblem
In nums, every number appears exactly twice except for one number that appears only once.
Return the number that appears once.
Aim for a linear-time solution that uses only a constant amount of extra space.
Constraints
- 1 ≤ nums.length ≤ 30000, and nums.length is odd
- 0 ≤ nums[i] ≤ 30000
- Exactly one value appears once; every other value appears exactly twice
Examples: pick one to animate
Solutions
TimeO(n)
SpaceO(1)
Time: One pass over the array, one XOR per element.
Space: One integer, x, no matter how long the array is.
XOR of a number with itself is 0, XOR with 0 changes nothing, and the order does not matter. So XOR-ing every number together cancels each pair and leaves only the number that appears once.