




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).
1function findTheDifference(s, t) {
2    const count = {};
3    for (const char of s) {
4        count[char] = (count[char] || 0) + 1;
5    }
6    for (const char of t) {
7        if (!count[char] || count[char] === 0) return char;
8        count[char]--;
9    }
10    return '';
11}
12
13console.log(findTheDifference('abcd', 'abcde')); // Output: e
14console.log(findTheDifference('', 'y')); // Output: yThis JavaScript solution uses an object to store counts of each character in s. It decrements the count in t, returning a character with a non-positive count, indicating the additional 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 Python solution XORs each character's ASCII value in both strings. Due to the associative property of XOR, paired characters’ XOR result in 0, leaving the additional character’s ASCII value as the final result.