Bit tricks let you replace whole data structures with a single integer. XOR is the classic: it is its own inverse, so pairs of equal numbers cancel out.
After laundry day every sock in the basket has a twin except one. The basket is the list nums of sock pattern numbers: each number appears exactly twice, apart from one number that appears only once. Write single_number(nums) that returns the pattern number of the unpaired sock.
Examples
Input: nums = [6, 6, 9]
Output: 9
Input: nums = [5, 8, 3, 8, 3]
Output: 5
Input: nums = [7]
Output: 7
Constraints
1 <= len(nums) <= 3 * 10**4- Every element appears twice except one, which appears once
- Target: O(n) time and O(1) extra space (a
Counterworks but is not the point)
Goals
- Use the properties of XOR (x ^ x == 0, x ^ 0 == x) to cancel out pairs
- Solve a counting problem in O(1) extra space instead of with a hash map