Find the Difference
You are given two strings s and t. String t is generated by randomly shuffling string s and then adding one more character at a random position. Find the character that was added to t.
A hash map solution counts characters in s, then decrements for characters in t. The character that has a count of -1 (or the one remaining after decrementing) is the added character. Alternatively, XOR of all characters in both strings cancels out the duplicates, leaving the added character.
For example, s = "abcd", t = "abcde" → the added character is 'e'.
The XOR approach (s XOR t) is more space-efficient at O(1), but the hash map approach is more generally applicable to problems where characters are not guaranteed to be letters. Both are valid solutions.
The XOR approach works because XOR of two identical values cancels out (a XOR a = 0). By XORing all characters in both strings, the duplicate characters cancel and only the added character remains. This uses O(1) space. However, the hash map approach is more general and works for any character set, not just lowercase letters.
The problem guarantees that t always contains exactly one extra character compared to s. Both strings consist only of lowercase English letters.
Example Input & Output
Single char added.
e is added.
Extra a added.
Algorithm Flow

Solution Approach
Count chars in s, decrement for t. The char with remaining count is the extra one.
Time O(n), Space O(1).
Best Answers
import java.util.*;
class Solution {
public char solution(String s, String t) {
int[] counts = new int[26];
for (char ch : s.toCharArray()) counts[ch - 'a']++;
for (char ch : t.toCharArray()) {
if (--counts[ch - 'a'] < 0) return ch;
}
return ' ';
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
