Member-only story

Leetcode — Programming Skills (Find The Difference) #2

Tomas Svojanovsky
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 string s into result. Since XORing a character with itself results in 0, if there were duplicate characters, their effect would cancel out
  • Since string t contains all characters from s plus one extra character, when XORing all characters from both s and t, 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

--

--

Tomas Svojanovsky
Tomas Svojanovsky

Written by Tomas Svojanovsky

I'm a full-stack developer. Programming isn't just my job but also my hobby. I like developing seamless user experiences and working on server-side complexities

No responses yet