389. Find the Difference
Description
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 + 1sandtconsist of lowercase English letters.
Solutions
Solution 1: Counting
Thinking
\(t\) is \(s\) shuffled plus one letter. A count difference finds it.
Count \(s\), decrement along \(t\); the first negative frequency is the extra letter.
We can use a hash table or array \(cnt\) to count the occurrence of each character in string \(s\), then traverse string \(t\). For each character, we subtract its occurrence in \(cnt\). If the corresponding count is negative, it means that the occurrence of this character in \(t\) is greater than in \(s\), so this character is the added character.
The time complexity is \(O(n)\), and the space complexity is \(O(|\Sigma|)\), where \(n\) is the length of the string, and \(\Sigma\) represents the character set. Here the character set is all lowercase letters, so \(|\Sigma|=26\).
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
Solution 2: Summation
Thinking
Counting uses \(O(\Sigma)\) space. The difference of ASCII sums is the extra code point, in \(O(1)\) space.
We can sum the ASCII values of each character in string \(t\), then subtract the sum of the ASCII values of each character in string \(s\). The final result is the ASCII value of the added character.
The time complexity is \(O(n)\), where \(n\) is the length of the string. The space complexity is \(O(1)\).
1 2 3 4 5 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 | |