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.This approach involves creating frequency counts for both strings. Loop through each character in both strings, updating a counter for each character. By comparing these counters, you can determine which character has a different count, revealing the additional character in string t.
This solution initializes an array of size 26 (for each letter in the English alphabet) to zero. It then iterates over string s, incrementing the count for each letter. It subsequently iterates over string t, decrementing the count. The first character that results in a non-positive count is the additional character.
C++
Java
Python
C#
JavaScript
The time complexity is O(n) where n is the length of s as we iterate over t once in the worst case. Space complexity is O(1) because the storage requirement is constant (the fixed size count array).
This approach leverages the properties of the XOR bitwise operator. XOR'ing the same numbers results in 0 and XOR is commutative and associative, meaning the order of operations doesn't matter. By XOR'ing all characters in both strings, one additional character will be left out, since all others cancel each other out.
The C solution iterates over each character in both s and t, applying the XOR operation between them. Given XOR's properties, each pair of identical characters across s and t will cancel each other out, leaving the extra character as the result.
C++
Java
Python
C#
JavaScript
Time complexity is O(n) as both strings are traversed. Space complexity is O(1) because only a single variable is used.
| Approach | Complexity |
|---|---|
| Frequency Count Approach | The time complexity is O(n) where n is the length of |
| XOR Approach | Time complexity is O(n) as both strings are traversed. Space complexity is O(1) because only a single variable is used. |
Find the Difference • Kevin Naughton Jr. • 19,863 views views
Watch 9 more video solutions →Practice Find the Difference with our built-in code editor and test cases.
Practice on FleetCode