I recently came across this question on Leetcode and figured out a solution that I need some clarification with:
Given an array of integers, every element appears twice except for one. Find that single one.
Note: Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
class Solution { public: int singleNumber(vector<int>& nums) { int result = 0; for(auto & c : nums) { result ^= c; } return result; } };
First of all, what sorts of keywords should I be paying attention to in order to figure out that I should be using an XOR operation for this question?
Also, why does XOR'ing all items in the vector with each other give us the one that is not repeated?
Thank you all for these responses, here is some more information on bitwise properties for anyone else interested: More bitwise info
XOR ( ^ ), or eXclusive OR, is a bitwise operator that returns true (1) for odd frequencies of 1. The XOR truth table is as follows: 1 ^ 1 = 0. 1 ^ 0 = 1.
There is no mathematical equivalent as XOR is a bitwise operation. They are not related to mathematics but to how computers handle numbers.
A ^ 0 == A
A ^ A == 0
A ^ B == B ^ A
(A ^ B) ^ C == A ^ (B ^ C)
(3) and (4) together mean that the order in which numbers are xor
ed doesn't matter.
Which means that, for example, A^B^X^C^B^A^C
is equal to A^A ^ B^B ^ C^C ^ X
.
Because of the (2) that is equal to 0^0^0^X
.
Because of the (1) that is equal to X
.
I don't think there are any specific keywords that can help you to identify such problems. You just should know above properties of XOR.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With