Member-only story
Unlock XOR Magic to Boost Your Coding Interview Skills
Master XOR tricks to solve problems faster and stand out!

If you get an XOR question in an interview, you need to know exactly how to do it!
As someone who has given their fair share of DSA interviews, let me give you some advice, you need to know these XOR techniques very well!
I have gotten this at least thrice in online programming contests and as subproblems in other complex DSA problems too many times.
Now, if you want to solve an XOR problem, you must have prior knowledge of these techniques. It is very hard to come up with these solutions by yourself during practice, let alone under the pressure of an interview! This article will look at some common XOR approaches/shortcuts to excel in DSA interview scenarios.
Understanding XOR Operations
XOR, a logical operation, returns true only when the operands are different and false when they are the same. In Python, the XOR operator is denoted as ‘^’.
XOR Operation has the following properties:
- Commutative:
a ^ b
is equal tob ^ a
. - Associative:
(a ^ b) ^ c
is equal toa ^ (b ^ c)
. - Identity:
a ^ 0
is equal toa
. - Inverse:
a ^ a
is equal to 0.
Finding the Odd Occurring Number
Determine the lone element occurring an odd number of times in an array where all other elements appear an even number of times.
def find_odd_occurrence(arr):
res = 0
for num in arr:
res ^= num
return res
arr = [4, 3, 6, 2, 2, 3, 4, 6, 7, 7, 8, 8, 8]
print("The element occurring odd number of times is:", find_odd_occurrence(arr))
Explanation:
- If two numbers are the same, their XOR is 0. If two numbers are different, their XOR is 1.
- For elements occurring an even number of times, they will eventually be paired with themselves and XORed, resulting in 0.
- The element occurring an odd number of times will not have a pair to cancel out its effect. Therefore, it will remain in
res
after all the…