• Time:O(n)
• Space:O(1)

C++

``````class Solution {
public:
char findTheDifference(string s, string t) {
char ans = 0;

for (const char c : s)
ans ^= c;

for (const char c : t)
ans ^= c;

return ans;
}
};
``````

JAVA

``````class Solution {
public char findTheDifference(String s, String t) {
char ans = 0;

for (final char c : s.toCharArray())
ans ^= c;

for (final char c : t.toCharArray())
ans ^= c;

return ans;
}
}
``````

Python

``````class Solution:
def findTheDifference(self, s: str, t: str) -> str:
count = Counter(s)

for i, c in enumerate(t):
count[c] -= 1
if count[c] == -1:
return c
``````

• Time:O(n)
• Space:O(1)

C++

``````class Solution {
public:
char findTheDifference(string s, string t) {
vector<int> count(128);

for (const char c : s)
++count[c];

for (const char c : t)
if (--count[c] < 0)
return c;

throw;
}
};
``````

JAVA

``````class Solution {
public char findTheDifference(String s, String t) {
int[] count = new int[128];

for (final char c : s.toCharArray())
++count[c];

for (final char c : t.toCharArray())
if (--count[c] < 0)
return c;

throw new IllegalArgumentException();
}
}
``````