DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Ganesh Shetty
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'.
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
sugandhaduhan23 profile image
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.
Image description

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.