Check two given strings are isomorphic in JavaScript
Last Updated :
03 Jul, 2024
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 second string replaces each character of the first 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 and every second string character. 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
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));
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
// JavaScript program for above approach
// Function to check isomorphic strings
function isIsomorphic(str1, str2) {
// If length of strings are not equal then
// they are not isomorphic
if (str1.length !== str2.length) {
return false;
}
// Map to store the mapping between
// characters of first string to second
const map = new Map();
// Set to store the already mapped
// character of second string
const set = new Set();
for (let i = 0; i < str1.length; i++) {
// Taking ith char from both strings
char1 = str1.charAt(i);
char2 = str2.charAt(i);
// If char1 has already been mapped
if (map.has(char1) == true) {
// Then we have to check that
// mapped char should be same
if (map.get(char1) !== char2) {
return false;
}
}
// If char1 is appearing for the first time
else {
// Check in the set that the char2
// is already there or not
if (set.has(char2)) {
return false;
}
// If none of above condition is true
// it means both char1 and char2 are
// appearing for the first time
// insert them into the map
map.set(char1, char2);
set.add(char2);
}
}
return true;
}
str1 = "ABCA";
str2 = "XYZX";
console.log(isIsomorphic(str1, str2));
Using Maps
Using two maps, one for each string, track character mappings. Iterate through both strings, checking if corresponding characters are mapped differently. If so, return false; otherwise, continue. If all mappings are consistent, return true.
Example: The function isStringIsomorphic checks if two strings str1 and str2 are isomorphic, i.e., if characters in str1 can be mapped uniquely to characters in str2, and vice versa.
JavaScript
function isStringIsomorphic(str1, str2) {
if (str1.length !== str2.length) {
return false;
}
const map1 = new Map();
const map2 = new Map();
for (let i = 0; i < str1.length; i++) {
const char1 = str1[i];
const char2 = str2[i];
if (map1.has(char1)) {
if (map1.get(char1) !== char2) {
return false;
}
} else {
map1.set(char1, char2);
}
if (map2.has(char2)) {
if (map2.get(char2) !== char1) {
return false;
}
} else {
map2.set(char2, char1);
}
}
return true;
}
const str1 = "ABCA";
const str2 = "XYZX";
console.log(isStringIsomorphic(str1, str2));
Using String Replacement and Comparison
Using string replacement and comparison to check if two strings are isomorphic involves mapping each character in both strings to a new unique character sequence. If the transformed sequences are identical, the strings are isomorphic.
Example
JavaScript
const areIsomorphic = (s, t) => {
const replaceChars = (str) => {
const map = {};
let newStr = '';
let charCode = 0;
for (let char of str) {
if (!map[char]) {
map[char] = String.fromCharCode(charCode++);
}
newStr += map[char];
}
return newStr;
};
return replaceChars(s) === replaceChars(t);
};
console.log(areIsomorphic("egg", "add")); // true
console.log(areIsomorphic("foo", "bar")); // false
Similar Reads
Check if Strings are Equal in JavaScript
These are the following ways to check for string equality in JavaScript: 1. Using strict equality operator - Mostly UsedThis operator checks for both value and type equality. it can be also called as strictly equal and is recommended to use it mostly instead of double equals. [GFGTABS] JavaScript le
2 min read
Check if a Given String is Binary String or Not in JavaScript
Binary strings are sequences of characters containing only the digits 0 and 1. Other than that no number can be considered as Binary Number. We are going to check whether the given string is Binary or not by checking it's every character present in the string. Example: Input: "101010"Output: True, b
4 min read
How to check a given string is an anagram of another string in JavaScript ?
In this article, we will learn how to check a given string is an anagram of another string in JavaScript. Before that, we should learn what is an anagram. An anagram is a word or sentence, which usually contains all the original letters exactly once, in order to arrange the letters of a different te
3 min read
Javascript Program to Check if a given string is Pangram or not
In this article, we are going to implement algorithms to check whether a given string is a pangram or not. Pangram strings are those strings that contain all the English alphabets in them. Example: Input: âFive or six big jet planes zoomed quickly by tower.â Output: is a Pangram Explanation: Does'no
7 min read
Convert Array to String in JavaScript
In JavaScript, converting an array to a string involves combining its elements into a single text output, often separated by a specified delimiter. This is useful for displaying array contents in a readable format or when storing data as a single string. The process can be customized to use differen
8 min read
Check if two strings are permutation of each other in JavaScript
In this approach, we are going to discuss how we can check if two strings are permutations of each other or not using JavaScript language. If two strings have the same number of characters rather than having the same position or not it will be a permutation. Example: Input: "pqrs" , "rpqs"Output: Tr
4 min read
JavaScript - How To Check if String Contains Only Digits?
A string with only digits means it consists solely of numeric characters (0-9) and contains no other characters or symbols. Here are the different methods to check if the string contains only digits. 1. Using Regular Expression (RegExp) with test() MethodThe most efficient way to check if a string c
3 min read
What are the builtin strings in JavaScript ?
A sequence of letters, special characters, numbers, etc., or a combination of all of them is known as a string. Strings are created by enclosing the string characters within a single quote (') or within double quotes ("). Syntax: var myString = 'Good Morning123!'; // Single quoted string var myStrin
3 min read
JavaScript - Compare the Case Insensitive Strings
Here are the different methods to compare the case-insensitive strings in JavaScript. 1. Using toLowerCase() or toUpperCase() MethodsThis is the most simple and used approach. Convert both strings to the same case and then compare them. [GFGTABS] JavaScript const comStr = (s1, s2) => s1.toLowerCa
2 min read
JavaScript - Convert String to Array
Strings in JavaScript are immutable (cannot be changed directly). However, arrays are mutable, allowing you to perform operations such as adding, removing, or modifying elements. Converting a string to an array makes it easier to: Access individual characters or substrings.Perform array operations s
5 min read