## DEV Community π©βπ»π¨βπ»

Ganesh Shetty

Posted on • Updated on

# How to find if two strings are isomorphic to each other in Javascript

Two strings str1 and str2 are called isomorphic if there is a one-to-one mapping possible for every character of str1 to every character of str2. And all occurrences of every character in βstr1β map to the same character in βstr2β.

``````Input:  str1 = "aab", str2 = "xxy"
Output: True
'a' is mapped to 'x' and 'b' is mapped to 'y'.

Input:  str1 = "aab", str2 = "xyz"
Output: False
One occurrence of 'a' in str1 has 'x' in str2 and
other occurrence of 'a' has 'y'.
``````

Solution is very simple , we will consider every character of βstr1β and check if all occurrences of it map to the same character in βstr2β.

We keep a hash map,We store each character in str1 as key and character in str2 for the same index as value,

``````<script>
function isIsomorphic(str1, str2) {
var obj = {};
for (let i = 0; i < str1.length; i++) {
if (!obj[str1[i]]) {
obj[str1[i]] = str2[i];
} else {
if (obj[str1[i]] !== str2[i]) {
return false;
}
}
}
return true;
}
console.log(isIsomorphic("abc", "xyz"));
</script>
``````

Hope this helps someone, Please comment if you need more such algorithm question in Javascript

## Top comments (1)

Sugandha Duhan

The above solution will not work for "badc", "baba". Also in isomorphic string if s1 can be mapped to s2, vice versa should also be true.

### π Friends don't let friends browse without dark mode.

Sorry, it's true.