Check two given strings are isomorphic in JavaScript
Last Updated :
17 Jul, 2023
Two strings are said to be isomorphic if it is possible to map every character of the first string to every character of the second string. Basically, in isomorphic strings, there is a one-to-one mapping between every character of the first string to every character of the second string. We can also explain this by saying that each character of the first string is replaced by each character of the second string.
Example 1:
str1 = 'ABCA'
str2 = 'XYZX'
'A' maps to 'X'
'B' maps to 'Y'
'C' maps to 'Z'
Here, mapping is possible between every character of the first string to every character of the second string. So str1 and str2 are isomorphic.
Example 2:
str1 = 'ABCA'
str2 = 'WXYZ'
'A' maps to 'W'
'B' maps to 'X'
'C' maps to 'Y'
'A' again maps to 'Z'
These two strings are not isomorphic because character ‘A’ from the first string is mapping with two characters from the second string.
We can check two given strings are isomorphic in Javascript in two ways:
- Using Naive Approach
- Using Hashmap
Approach 1: Using Naive Approach
In this approach, we will compare each character of the first string with another character of the first string likewise for the second string. The current character of both strings shouldn’t be equal to other characters. The time complexity of this approach is O(N^2) where n is the length of the string. This is a brute-force approach which is not very efficient.
This is the implementation of the above approach.
Javascript
function isStringIsomorphic(str1, str2) {
if (str1.length !== str2.length) {
return false ;
}
for (let i = 0; i < str1.length; i++) {
for (let j = i + 1; j < str1.length; j++) {
if (
(str1[i] === str1[j] &&
str2[i] !== str2[j]) ||
(str1[i] !== str1[j] &&
str2[i] === str2[j])
) {
return false ;
}
}
}
return true ;
}
str1 = "ABCA" ;
str2 = "XYZX" ;
console.log(isStringIsomorphic(str1,str2));
|
Approach 2: By using hashmap
To check if strings are isomorphic or not, we have to take care of the following conditions:
- The length of both strings should be equal
- The current character of both strings shouldn’t be mapped with other characters already.
We will use a hashmap to store the mapping between characters from str1 to those of str2. We will also use a Set to store the already mapped characters of str2.
Below is the implementation of the above approach.
Javascript
function isIsomorphic(str1, str2) {
if (str1.length !== str2.length) {
return false ;
}
const map = new Map();
const set = new Set();
for (let i = 0; i < str1.length; i++) {
char1 = str1.charAt(i);
char2 = str2.charAt(i);
if (map.has(char1) == true ) {
if (map.get(char1) !== char2) {
return false ;
}
}
else {
if (set.has(char2)) {
return false ;
}
map.set(char1, char2);
set.add(char2);
}
}
return true ;
}
str1 = "ABCA" ;
str2 = "XYZX" ;
console.log(isIsomorphic(str1, str2));
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...