Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Check two given strings are isomorphic in JavaScript
Next article icon

Check two given strings are isomorphic in JavaScript

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Table of Content

  • Using Naive Approach
  • By using hashmap
  • Using Maps
  • Using String Replacement and Comparison

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)); 

Output
true

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)); 

Output
true

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)); 

Output
true 

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 

Output
true false 

Next Article
Check two given strings are isomorphic in JavaScript

H

hritikrommie
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • Data Structures
  • javascript-string
  • JavaScript-DSA
  • JavaScript-Questions
Practice Tags :
  • Data Structures

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.JavaScriptlet s1 = 'abc';
    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, bin
    3 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 ter
    3 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
    7 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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences