Single Number Problem
Description
LeetCode Problem 136.
Given a non-emptyarray of integers nums, every element appears twice except for one. Find that single one.
You mustimplement a solution with a linear runtime complexity and useonly constantextra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Input: nums = [1]
Output: 1
Constraints:
- 1 <= nums.length <= 3 * 10^4
- -3 * 10^4 <= nums[i] <= 3 * 10^4
- Each element in the array appears twice except for one element which appears only once.
Solution
Approach: XOR
A hash set or sorting would find the single number, but they need O(n) extra space or O(n log n) time. Bitwise XOR does it in one pass with a single variable, thanks to three properties:
x ^ x = 0: a number XORed with itself cancels out.x ^ 0 = x: XOR with 0 changes nothing.- XOR is commutative and associative, so the order of the numbers does not matter.
Start with result = 0 and XOR every number into it. Each number that appears twice cancels itself out, wherever its two copies are in the array, and only the single number remains.
For nums = [4, 1, 2, 1, 2]:
4 ^ 1 ^ 2 ^ 1 ^ 2 = 4 ^ (1 ^ 1) ^ (2 ^ 2) = 4 ^ 0 ^ 0 = 4
Negative numbers need no special case: XOR works on their bits the same way.
Complexity: O(n) time and O(1) extra space, where n is the length of nums.
class Solution:
def singleNumber(self, nums: List[int]) -> int:
result = 0
for num in nums:
result ^= num # x ^ x == 0, so every pair cancels out
return result
Now write it from memory
Close the write-up and solve it yourself against the tests.