




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).
1#include <stdio.h>
2#include <string.h>
3
4char findTheDifference(char* s, char* t) {
5    int count[26] = {0};
6    while (*s) count[*s++ - 'a']++;
7    while (*t) {
8        if (count[*t - 'a']-- == 0)
9            return *t;
10        t++;
11    }
12    return '\0';
13}
14
15int main() {
16    printf("%c\n", findTheDifference("abcd", "abcde"));  // Output: e
17    printf("%c\n", findTheDifference("", "y"));  // Output: y
18    return 0;
19}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.
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.
1using namespace std;
char findTheDifference(string s, string t) {
    char diff = 0;
    for (char c : s) diff ^= c;
    for (char c : t) diff ^= c;
    return diff;
}
int main() {
    cout << findTheDifference("abcd", "abcde") << endl;  // Output: e
    cout << findTheDifference("", "y") << endl;  // Output: y
    return 0;
}The C++ solution uses a single variable to XOR all characters from both strings. Characters that appear twice (once in each string equally) will zero out, and only the additional character in t remains.