LeetCode Solutions

389. Find the Difference

Time: $O(n)$

Space: $O(1)$

			

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;
  }
};
			

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;
  }
}
			

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