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 <= 1000t.length == s.length + 1s and t consist of lowercase English letters.String t is formed by shuffling string s and adding one extra character. By counting the frequency of each character in both strings, the added character will have a higher count in t than in s. We can compare these counts to find the difference.
s and t.countT[i] > countS[i] is the answer.Instead of using two separate count arrays, we can use a single array. First count all characters from t, then subtract counts for characters in s. The character left with count 1 is the added character.
t.s.1.After sorting both strings, corresponding characters at each position should match since t is a shuffled version of s plus one character. The first position where they differ reveals the added character. If all positions match, the added character is at the end of t.
s and t.t that differs from the corresponding character in s.t.Each character has an ASCII value. If we sum the ASCII values of all characters in t and subtract the sum of ASCII values in s, the result equals the ASCII value of the added character. This works because all matching characters cancel out.
s.t.sumS from sumT.We can optimize space by using a single variable instead of two separate sums. By subtracting ASCII values from s and adding ASCII values from t to the same variable, we compute the difference in one pass through both strings.
res = 0.s, subtract its ASCII value from res.t, add its ASCII value to res.res to a character and return it.XOR has a useful property: a ^ a = 0 and a ^ 0 = a. If we XOR all characters from both strings together, each character that appears in both s and t will cancel out (XOR with itself gives 0). The only character remaining is the added one, since it appears an odd number of times total.
res = 0.res with each character's ASCII value in s.res with each character's ASCII value in t.res to a character and return it.sWhen s is an empty string, t contains exactly one character (the added one). Solutions that iterate through s first or rely on finding a mismatch between sorted strings must handle this edge case. The XOR and sum-based approaches naturally handle this since XORing or summing over an empty string contributes nothing.
A common mistake is to iterate through both strings and return the first character in t that does not appear in s. This fails when the added character is a duplicate of an existing character. For example, if s = "a" and t = "aa", the added character is 'a', but a naive check would miss it since 'a' already exists in s.