Skip to content

389. Find the Difference 👍

Approach 1: Bit

  • Time: $O(n)$
  • Space: $O(1)$
1
2
3
4
5
6
7
8
class Solution {
 public:
  char findTheDifference(string s, string t) {
    const char sXors = accumulate(s.begin(), s.end(), 0, bit_xor<>());
    const char tXors = accumulate(t.begin(), t.end(), 0, bit_xor<>());
    return sXors ^ tXors;
  }
};
1
2
3
4
5
6
7
class Solution {
  public char findTheDifference(String s, String t) {
    final char sXors = (char) s.chars().reduce(0, (a, b) -> a ^ b);
    final char tXors = (char) t.chars().reduce(0, (a, b) -> a ^ b);
    return (char) (sXors ^ tXors);
  }
}
1
2
3
4
5
class Solution:
  def findTheDifference(self, s: str, t: str) -> str:
    sXors = chr(functools.reduce(operator.xor, map(ord, s), 0))
    tXors = chr(functools.reduce(operator.xor, map(ord, t), 0))
    return chr(ord(sXors) ^ ord(tXors))

Approach 2: Hash Table

  • Time: $O(n)$
  • Space: $O(26) = O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
 public:
  char findTheDifference(string s, string t) {
    vector<int> count(26);

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

    for (const char c : t) {
      if (count[c - 'a'] == 0)
        return c;
      --count[c - 'a'];
    }

    throw;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
  public char findTheDifference(String s, String t) {
    int[] count = new int[26];

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

    for (final char c : t.toCharArray()) {
      if (count[c - 'a'] == 0)
        return c;
      --count[c - 'a'];
    }

    throw new IllegalArgumentException();
  }
}
1
2
3
4
5
6
7
8
class Solution:
  def findTheDifference(self, s: str, t: str) -> str:
    count = collections.Counter(s)

    for c in t:
      if count[c] == 0:
        return c
      count[c] -= 1