Top Interview 150
The Isomorphic Strings problem is a string mapping challenge that involves character substitutions while preserving order. Let’s solve LeetCode 205: Isomorphic Strings step by step.
🚀 Problem Description
Two strings s
and t
are isomorphic if:
- Each character in
s
can be replaced by a unique character int
. - The order of characters in
s
is preserved int
. - No two characters in
s
map to the same character int
, and vice versa.
💡 Examples
Example 1
Input: s = "egg", t = "add"
Output: true
Explanation: 'e' maps to 'a', 'g' maps to 'd'.
Example 2
Input: s = "foo", t = "bar"
Output: false
Explanation: 'o' would need to map to both 'a' and 'r'.
Example 3
Input: s = "paper", t = "title"
Output: true
Explanation: 'p' maps to 't', 'a' maps to 'i', etc.
🏆 JavaScript Solution
We solve this problem using two hash maps:
- To map characters from
s
tot
. - To ensure no two characters in
s
map to the same character int
.
Implementation
var isIsomorphic = function(s, t) {
if (s.length !== t.length) return false;
const mapST = {};
const mapTS = {};
for (let i = 0; i < s.length; i++) {
const charS = s[i];
const charT = t[i];
if ((mapST[charS] && mapST[charS] !== charT) ||
(mapTS[charT] && mapTS[charT] !== charS)) {
return false;
}
mapST[charS] = charT;
mapTS[charT] = charS;
}
return true;
};
🔍 How It Works
-
Check Lengths:
- If the strings have different lengths, they cannot be isomorphic.
-
Use Two Maps:
-
mapST
: Maps characters ins
to characters int
. -
mapTS
: Maps characters int
to characters ins
.
-
-
Traverse Characters:
- For each pair of characters in
s
andt
, check if the mappings are consistent. - If not, return
false
.
- For each pair of characters in
-
Return
true
:- If all characters are mapped consistently, the strings are isomorphic.
🔑 Complexity Analysis
-
Time Complexity:
O(n)
, wheren
is the length ofs
(ort
).- Each character is processed once.
Space Complexity:
O(1)
, since the hash maps can store at most256
entries (ASCII characters).
📋 Dry Run
Output: true
✨ Pro Tips for Interviews
-
Edge Cases:
- Different lengths:
s = "abc"
,t = "ab"
. - Single-character strings:
s = "a"
,t = "a"
. - Repeated characters:
s = "aaa"
,t = "bbb"
.
- Different lengths:
-
Discuss Two Maps:
- Emphasize the need for bidirectional mapping to avoid conflicts.
-
Optimization:
- Highlight how this approach works in
_O(n)_
, which is optimal for this problem.
- Highlight how this approach works in
📚 Learn More
Check out the full explanation and code walkthrough on my previous Dev.to post:
👉 Ransom Note - JavaScript Solution
What’s your preferred method to solve this problem? Let’s discuss! 🚀
Follow Me on GitHub 🚀
If you found this solution helpful, check out more of my projects and solutions on my GitHub profile.
Don't forget to follow for more updates!