Find the Difference

XOR all characters of both strings — the lone unmatched char survives.

Easy
Time O(n) Space O(1)
LeetCode
2 min read
bit-manipulation xor string

Problem#

t is s shuffled with one extra random letter added. Return the added letter.

Examples#

  • s="abcd", t="abcde"'e'.
  • s="", t="y"'y'.

Constraints#

  • 0 <= s.length <= 1000, t.length = s.length + 1, lowercase only.

Approach#

XOR every character of s and t together. Pairs cancel, leaving the lone added char.

Solution#

Find the Difference
class Solution {
public:
char findTheDifference(string s, string t) {
char x = 0;
for (char c : s) x ^= c;
for (char c : t) x ^= c;
return x;
}
};

Editorial#

XOR’s self-inverse property turns “find the unmatched” into a one-pass fold. Equivalent to summing/subtracting char codes but cleaner because it avoids overflow concerns and works for any character set.

Complexity#

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

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.