Find the Difference (LeetCode 389): Solution and Explanation
String t is string s shuffled with one extra lowercase letter inserted somewhere. Return that extra letter.
Intuition
Every letter in s also appears in t. If you lay both strings side by side, each letter of s has a partner in t, and exactly one letter of t has no partner.
Counting letters would find it, but there is a trick that needs no table at all. XOR has two useful properties: c ^ c = 0 and c ^ 0 = c, and the order of the operands does not matter.
So XOR the character codes of every letter in both strings. Each letter of s is XORed in twice, once from s and once from t, and disappears. The extra letter is XORed in once and is all that remains.
Because XOR does not care about order, the shuffle does not matter either. The accumulator always equals the XOR of the letters that have been seen an odd number of times so far.
Approach: XOR all character codes
- Start with
x = 0. - For every character
cins, dox ^= c. - For every character
cint, dox ^= c. - Return
xconverted back to a character.
Step-by-step example
s = "abcd", t = "abcde"
- x starts at 0.
- XOR in a, b, c, d from s: x = 97 ^ 98 ^ 99 ^ 100 = 4 (00000100).
- XOR in a, b, c, d from t: each one cancels its copy from s, and x returns to 0.
- XOR in e from t: x = 0 ^ 101 = 101 (01100101).
- 101 is the code of 'e', so the function returns 'e'.
Code: Python, Java, C++
1class Solution:
2 def findTheDifference(self, s: str, t: str) -> str:
3 x = 0
4 for c in s:
5 x ^= ord(c)
6 for c in t:
7 x ^= ord(c)
8 return chr(x)1class Solution {
2 public char findTheDifference(String s, String t) {
3 int x = 0;
4 for (char c : s.toCharArray()) {
5 x ^= c;
6 }
7 for (char c : t.toCharArray()) {
8 x ^= c;
9 }
10 return (char) x;
11 }
12}1class Solution {
2public:
3 char findTheDifference(string s, string t) {
4 int x = 0;
5 for (char c : s) {
6 x ^= c;
7 }
8 for (char c : t) {
9 x ^= c;
10 }
11 return (char) x;
12 }
13};Time and space complexity
O(n)
Each character of s and t is visited once, with one XOR per character.
O(1)
A single integer accumulator.
Other approaches
Count letters (time O(n), space O(1))
Count the 26 letters in t, subtract the counts from s, and return the letter whose count is left at 1. Easy to read; the array has a fixed size of 26.
Sum of codes (time O(n), space O(1))
Return the character whose code is sum(t) - sum(s). It works for the same reason as XOR, with addition instead, and sums stay small for strings of length 1000.
Sort both strings (time O(n log n), space O(n))
Sort s and t and return the first position where they differ, or the last letter of t. Simple but slower.
Common mistakes
- Returning the first letter of t that is not in s. The extra letter can be a duplicate of one already in s, as in s = "ae", t = "aea".
- Forgetting the empty s case. With s = "", the answer is simply t's only letter, which the XOR handles with no special case.
- Comparing letters position by position. t is shuffled, so positions in s and t do not line up.
- In Python, XORing the strings directly. Convert with ord before XOR and back with chr at the end.
Frequently asked questions
Why does XOR find the extra letter even when it repeats a letter in s?
If the extra letter is 'a' and s already has one 'a', then 'a' appears three times in total. Two of those cancel and one remains, so x still ends at 'a'.
Is XOR better than summing the codes?
Both are O(n) with O(1) space. XOR can never overflow, while a sum could in principle on very long strings. Here the strings are short, so either works.
How is this related to Single Number?
It is the same idea. Concatenate s and t and every letter appears an even number of times except one, which is exactly the Single Number setup.