Member-only story
Leetcode — Programming Skills (Find The Difference) #2
2 min readAug 19, 2024
There are multiple solutions to this problem, but I chose the one that was the hardest for me.
The Problem
Solution
I was initially afraid of bit manipulation because we don’t see it much in regular code, but it’s not that hard.
We’ll use the bitwise XOR operation on all the elements. XOR helps eliminate the duplicates, leaving only the odd one out.
0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 0 = 1
1 ^ 1 = 0
When all the other similar pairs
just even out or reduce to a zero, the different one would remain.
- The variable
result
is initialized to'\0'
(null character, which is 0 in terms of its ASCII value). This serves as the starting point for the XOR operations - The first
foreach
loop XORs all characters of strings
intoresult
. Since XORing a character with itself results in0
, if there were duplicate characters, their effect would cancel out - Since string
t
contains all characters froms
plus one extra character, when XORing all characters from boths
andt
, the characters common to both will cancel out (because x⊕x=0) - The only character that won’t be canceled out is the extra character in
t
that is not present in s