Isomorphic Strings

Try to solve the Isomorphic Strings problem.

Statement#

Given two strings, check whether two strings are isomorphic to each other or not.  Two strings are isomorphic if a fixed mapping exists from the characters of one string to the characters of the other string. For example, if there are two instances of the character "a"  in the first string, both these instances should be converted to another character (which could also remain the same character if "a" is mapped to itself) in the second string. This converted character should remain the same in both positions of the second string since there is a fixed mapping from the character "a" in the first string to the converted character in the second string.

Note: Two different characters cannot map to the same character. Furthermore, all the instances of a character must be replaced with another character while protecting the order of characters.

Constraints:

  • Both the strings consist of valid ASCII characters.

  • The length of the string is 00 \leq length \leq 5×1045 \times10^{4}.

  • The length of both strings is the same.

Examples#

Created with Fabric.js 3.6.6 Input string1 "egg" string2 "all" Result True Output Sample example 1

1 of 2

Created with Fabric.js 3.6.6 Output string1 "lol" string2 "ban" Input Result False Sample example 2

2 of 2

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check that you’re solving the correct problem:

Isomorphic strings

1

What is the output, if the following strings are given as an input?

string1 = “ACAB”

string2 = “XCXY”

A)

True

B)

False

Question 1 of 40 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Create two hash maps. One to store mapping from string1 to string2 and another to store mapping from string2 to string1.

Before storing the mapping of characters in the hash maps, first check if the character is present in its hash map.

If the character is already in the hash map, and is mapped to a different character in the hash map than the character to be mapped, the algorithm terminates and FALSE is returned.

If all the mappings are valid in both the hash maps, TRUE is returned.


Try it yourself#

Implement your solution in the following coding playground:

Python
usercode > main.py
Input #1
Input #2
Isomorphic Strings

Hash Maps: Introduction

Solution: Isomorphic Strings