




Sponsored
Sponsored
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.
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).
1def findTheDifference(s, t):
2    count = {}
3    for char in s:
4        count[char] = count.get(char, 0) + 1
5    for char in t:
6        if count.get(char, 0) == 0:
7            return char
8        count[char] -= 1
9
10print(findTheDifference("abcd", "abcde"))  # Output: e
11print(findTheDifference("", "y"))  # Output: yThe Python solution uses a dictionary to count the occurrences of each character in s. It then decrements this count for each character in t until an entry has a zero count, identifying the added character.
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.
Time complexity is O(n) as both strings are traversed. Space complexity is O(1) because only a single variable is used.
1
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.