LeetCode 389 - Find the Difference
You are given two strings s
and t
where t
is generated by randomly shuffling string s
and then adding one more letter at a random position. Return the letter that was added to t
.
Input: s = "abcd", t = "abcde"
Output: "e"
0 <= s.length <= 1000
t.length == s.length + 1
s
and t
consist of lowercase English letters.t
?
To solve this problem, we can use the following approaches:
We’ll count the frequency of each character in both strings s
and t
. The character that has a higher count in t
than in s
is the added character.
Calculate the sum of ASCII values of the characters in s
and t
. The difference between the two sums will be the ASCII value of the added character.
We can use bitwise XOR to solve this problem. When two identical bits are XOR’d, the result is 0. Hence, XOR of all characters in s
and t
will cancel out identical characters, and the result will be the added character.
All the approaches are efficient, but the XOR approach is both time-efficient and space-efficient.
s
.We’ll implement the XOR approach here:
def findTheDifference(s: str, t: str) -> str:
result = 0
for char in s:
result ^= ord(char)
for char in t:
result ^= ord(char)
return chr(result)
# Test Case
print(findTheDifference("abcd", "abcde")) # Output: "e"
result
to 0.s
with result
.t
with result
.result
will be the ASCII value of the added character.chr()
function and return it.This solution efficiently finds the extra character with linear time complexity and constant space complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?