uses XOR. Keep in mind:
- x ^ x = 0
- x ^ 0 = x
- XOR is commutative and associative
class Solution {
public int singleNumber(int[] array) {
int result = 0;
for (int num : array) {
result = result ^ num; // ^ is XOR operator
}
return result;
}
}
- Time Complexity: O(n)
- Space Complexity: O(1)