Find the Difference - Problem

You are given two strings s and t.

String t is generated by randomly shuffling string s and then adding one more letter at a random position.

Return the letter that was added to t.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcd", t = "abcde"
Output: "e"
💡 Note: The letter 'e' was added to the end of string s to create string t.
Example 2 — Added in Middle
$ Input: s = "abc", t = "abcd"
Output: "d"
💡 Note: The letter 'd' was added to string s. Even though t is shuffled, we can detect the extra character.
Example 3 — Single Character
$ Input: s = "", t = "y"
Output: "y"
💡 Note: Edge case: empty string s, 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

Visualization

Tap to expand
Find the Difference INPUT String s (original) a b c d String t (shuffled + 1) a b c d e Input Values: s = "abcd" t = "abcde" len(s)=4, len(t)=5 ALGORITHM STEPS 1 XOR Approach XOR all chars in s and t 2 Same chars cancel a^a=0, b^b=0, etc. 3 Only extra remains Result = added char 4 Return result Convert to char XOR Operation: a^b^c^d (from s) ^a^b^c^d^e (from t) = 0^0^0^0^e = e Time: O(n), Space: O(1) FINAL RESULT The added letter is: e Output: "e" OK - Verified 'e' was added to "abcd" to create "abcde" Key Insight: XOR has the property that a^a=0 and a^0=a. By XORing all characters from both strings, matching pairs cancel out (become 0), leaving only the extra character. This achieves O(1) space! TutorialsPoint - Find the Difference | Optimal Solution (XOR)
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
185.0K Views
Medium Frequency
~15 min Avg. Time
2.2K 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