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
๐Ÿ” The Magic Scanner MethodCollection S"abc"abcCollection T"abdc"abdc๐Ÿ” Magic ScannerXOR OperationIdentical items cancel out!Scan both collectionsScanner Process: aโŠ•bโŠ•cโŠ•aโŠ•bโŠ•dโŠ•caโŠ•a= 0bโŠ•b= 0cโŠ•c= 0dRemains!dFound the extra item!
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!
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28
89.5K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen