Find the Difference - Problem
Imagine you have two strings: s and t. Here's what happened - someone took string s, randomly shuffled all its characters around, and then sneakily added one extra character at a random position to create string t.
Your mission: Find that one extra character!
Example: If s = "abc" and t = "abcd", then the extra character is 'd'.
The challenge is that the characters in t are shuffled, so t might look like "cadb" instead of "abcd". You need to identify which character appears one more time in t than in s.
Input & Output
example_1.py โ Basic Case
$
Input:
s = "abcd", t = "abcde"
โบ
Output:
"e"
๐ก Note:
String t has all characters from s plus an extra 'e' at the end
example_2.py โ Shuffled Order
$
Input:
s = "abc", t = "cadb"
โบ
Output:
"d"
๐ก Note:
String s = 'abc' becomes t = 'cadb' with 'd' added and characters shuffled
example_3.py โ Single Character
$
Input:
s = "", t = "y"
โบ
Output:
"y"
๐ก Note:
Edge case where s is empty and t contains only the added character 'y'
Constraints
- 0 โค s.length โค 1000
- t.length == s.length + 1
- s and t consist of lowercase English letters only
- Follow up: How would you solve it if the strings contain unicode characters?
Visualization
Tap to expand
Understanding the Visualization
1
Initialize Scanner
Start with scanner result = 0 (empty)
2
Scan Collection S
Scanner reads: 'a', 'b', 'c' and stores their combined signature
3
Scan Collection T
Scanner reads: 'a', 'b', 'd', 'c' and processes against stored signature
4
Magic Cancellation
Identical items ('a', 'b', 'c') cancel out automatically
5
Result
Only the extra item 'd' remains on the scanner display!
Key Takeaway
๐ฏ Key Insight: XOR has the magical property that any value XORed with itself equals zero (a โ a = 0). This allows identical characters to cancel each other out, leaving only the unique character!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code