Problem Description
Given a non-empty array of integers where every element appears twice except for one, find the unique element that appears only once.
Key Insights
- Using bitwise XOR: XOR-ing a number with itself cancels out to 0.
- XOR is both commutative and associative, so the order of operations does not matter.
- A single traversal (linear time) and constant extra space is sufficient for solving the problem.
Space and Time Complexity
Time Complexity: O(n) – We only traverse the array once. Space Complexity: O(1) – Only a single extra variable is used regardless of input size.
Solution
We can solve this problem by initializing a variable to 0 and then traversing the array while XOR-ing each element with the variable. Due to the properties of XOR, pairs of identical numbers will cancel each other out (x XOR x = 0) and the unique number will be left as the final result. This approach uses constant extra space and performs in linear time.