🔗 Problem Link
LeetCode 389 – Find the Difference
👉 https://leetcode.com/problems/find-the-difference/
Introduction
This is a very clever problem.
At first glance, you might think:
- Use a HashMap
- Count frequencies
- Compare both strings
But there’s a much smarter and cleaner way to solve it using character arithmetic (ASCII values).
This problem teaches an important lesson:
Sometimes math can replace extra space.
Let’s break it down.
📌 Problem Understanding
You are given two strings:
st
String t is created by:
- Shuffling string
s - Adding one extra character at a random position
Your task:
Return the extra character added to t.Example 1
Example 2
🧠 First Intuition (Brute Force Thinking)
When solving this for the first time, a common approach would be:
- Count frequency of characters in
s - Count frequency of characters in
t - Compare both
- The one with extra count is the answer
That works in O(n) time and O(26) space.
But we can do better.
🚀 Smarter Approach – ASCII Sum Trick
💡 Key Insight
Characters are stored as integer ASCII values.
If:
- We add all ASCII values of characters in
t - Subtract all ASCII values of characters in
s
What remains?
👉 The ASCII value of the extra character.
Because:
All matching characters cancel out.
Only the added character remains.
💻 Your Code
🔍 Step-by-Step Explanation
1️⃣ Initialize Total
This will store the running ASCII difference.
2️⃣ Add All Characters of t
We add ASCII values of every character in t.
3️⃣ Subtract All Characters of s
We subtract ASCII values of every character in s.
4️⃣ Return Remaining Character
After subtraction, only the extra character’s ASCII value remains.
We convert it back to char.
🎯 Why This Works
Let’s take example:
ASCII Sum:
Subtract:
Everything cancels except the extra letter.
Simple and powerful.
⏱ Complexity Analysis
Time Complexity: O(n)
- One loop over
t - One loop over
s
Space Complexity: O(1)
No extra data structure used.
🔥 Even Smarter Approach – XOR Trick
Another elegant method is using XOR:
Why XOR Works?
Properties:
a ^ a = 0a ^ 0 = a- XOR is commutative
If we XOR all characters in both strings:
Matching characters cancel out.
Only the extra character remains.
XOR Version
This is considered the most elegant solution.
🏁 Final Thoughts
This problem teaches:
- Thinking beyond brute force
- Using mathematical properties
- Understanding ASCII representation
- Using XOR smartly
Sometimes the best solution is not about data structures —
it’s about recognizing hidden math patterns.




