




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).
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5    public char FindTheDifference(string s, string t) {
6        Dictionary<char, int> count = new Dictionary<char, int>();
7        foreach (char c in s) {
8            if (count.ContainsKey(c)) count[c]++;
9            else count[c] = 1;
10        }
11        foreach (char c in t) {
12            if (!count.ContainsKey(c) || count[c] == 0) return c;
13            count[c]--;
14        }
15        return '\0';
16    }
17
18    public static void Main(string[] args) {
19        Solution sol = new Solution();
20        Console.WriteLine(sol.FindTheDifference("abcd", "abcde"));  // Output: e
21        Console.WriteLine(sol.FindTheDifference("", "y"));  // Output: y
22    }
23}The C# solution uses a Dictionary to maintain counts for characters in s. It decrements these counts in t until it finds a character with insufficient count, which indicates 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
public class Solution {
    public char FindTheDifference(string s, string t) {
        char diff = '\0';
        foreach (char c in s) diff ^= c;
        foreach (char c in t) diff ^= c;
        return diff;
    }
    public static void Main(string[] args) {
        Solution sol = new Solution();
        Console.WriteLine(sol.FindTheDifference("abcd", "abcde"));  // Output: e
        Console.WriteLine(sol.FindTheDifference("", "y"));  // Output: y
    }
}This C# approach uses a combined XOR across characters in both strings. An extra character will remain uniquely due to its unmatched presence.