You are given two strings s
and t
.
String t
is generated by random shuffling string s
and then add one more letter at a random position.
Return the letter that was added to t
.
Example 1:
Input: s = "abcd", t = "abcde" Output: "e" Explanation: 'e' is the letter that was added.
Example 2:
Input: s = "", t = "y" Output: "y"
Constraints:
0 <= s.length <= 1000
t.length == s.length + 1
s
and t
consist of lowercase English letters.The problem asks to find the character that's added to string s
to form string t
. We'll explore two efficient solutions: counting and summation.
Approach: This approach uses a frequency counter (hash table or array) to track character counts in s
. It then iterates through t
, decrementing counts. The first character with a negative count is the added character because it appears more often in t
than in s
.
Code (Python):
from collections import Counter
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
cnt = Counter(s)
for c in t:
cnt[c] -= 1
if cnt[c] < 0:
return c
Time Complexity: O(m + n), where m and n are the lengths of s and t respectively. We iterate through both strings once.
Space Complexity: O(1). The Counter
in Python uses a hash table, but the size is limited to 26 (lowercase English letters), making space complexity constant.
Approach: This clever solution leverages the ASCII values of characters. The sum of ASCII values in t
minus the sum of ASCII values in s
equals the ASCII value of the added character.
Code (Python):
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
return chr(sum(ord(c) for c in t) - sum(ord(c) for c in s))
Time Complexity: O(m + n). We iterate through both strings once to calculate sums.
Space Complexity: O(1). We only use a few integer variables; space usage is constant.
Alternative Summation using XOR:
A more efficient variation of the summation approach uses the bitwise XOR operator (^
). The XOR of a number with itself is 0. Therefore, XORing all characters in s
and t
cancels out the common characters, leaving only the added character.
Code (Python):
class Solution:
def findTheDifference(self, s: str, t: str) -> str:
result = 0
for char in s:
result ^= ord(char)
for char in t:
result ^= ord(char)
return chr(result)
Time Complexity: O(m + n). We iterate through both strings once.
Space Complexity: O(1). Constant space is used.
Choosing the Best Solution:
The summation approach using XOR is generally preferred due to its slightly better performance and elegant use of bitwise operations. However, all three approaches have similar time and space complexities, making the choice often a matter of coding style preference. The counting method might be slightly easier to understand for beginners.