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 ele
The Xor operator is commutative:
1. X ⊕ Y = Y ⊕ X for any integers X and Y
and associative:
2. X ⊕ (Y ⊕ Z) = (X ⊕ Y) ⊕ Z for any integers X, Y and Z
It follows that the result of any sequence of xor
operations is completely independent of the order of the operands (that is, the order of the elements in the array).
3. X ⊕ X = 0 for any integer X
4. X ⊕ 0 = 0 ⊕ X = X for any integer X
In the problem we have an expression where each element Ai appears twice except some singular element B. the resulting Xor operation is equivalent to:
(A1 ⊕ A1) ⊕ (A2 ⊕ A2) ⊕ ... ⊕ B
=
0 ⊕ 0 ⊕ ... ⊕ B
=
B
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
Some problems can be solved quickly using bit manipulation. After familiarizing with Boolean operators and their properties, and seeing enough applications like this one, you will naturally "feel" when they're useful to solve a given problem.