Problem Description
You are given two strings s and t. String t is generated by randomly shuffling string s and then adding one extra letter at a random position. The task is to return the extra letter that was added to t.
Key Insights
- The problem guarantees that t has exactly one more character than s.
- Each character in s appears in t, except for the one additional character.
- Using XOR: XORing all characters in s and t cancels out the common ones, leaving the extra character.
- Alternative approaches include using a hash table (frequency counting) or sorting both strings.
Space and Time Complexity
Time Complexity: O(n), where n is the length of string t. Space Complexity: O(1) when using the XOR or summation method.
Solution
We can solve this problem efficiently using the XOR operation. The idea is that XORing a number with itself cancels out to zero. By XORing the ASCII codes of all characters in s and t, the characters that occur in both will cancel out, leaving only the ASCII code of the additional character. This approach uses constant space and runs in linear time.