136. Single Number
Summary
Problem
Difficulty: Easy
Tags: Array, Bit Manipulation
Intuition
This is fascinating. I had no idea about how to solve this program. the constraint was very strict, which was use constant memory and use linear time. so I saw the hint and search about XOR operator’s property.
Approach
The approach to this problem is more Mathematical. There are four key property of XOR operator to solve this problem.
- identity of XOR is 0 :
- XOR is Commutative :
- XOR is Associative :
- XOR is self-inversive :
from these property, we can figure it out if you XOR all the element of nums, you can get the unique one. ex) nums = [3, 7, 3] (Commutativity) (self-inverse) (identity \space of XOR)
Solution
int singleNumber(int* nums, int numsSize) {
int ans = 0;
for(int i = 0; i < numsSize; i++){
ans = ans ^ nums[i];
}
return ans;
}
Complexity
- Time: - Space complexity:
Thoughts
I like this question, but I don’t like it at the same time. it made me do some mathematical thinking about the XOR operator, and I loved it. However, If i don’t know the property of XOR operator, I will never find the solution to this question. And that is pretty annoying.