Isomorphic Strings | Practice | GeeksforGeeks

Given two strings 'str1' and 'str2', check if these two strings are isomorphic to each other.
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 while preserving the order.
Note: All occurrences of every character in ‘str1’ should map to the same character in ‘str2’
Example 1:
Input:
str1 = aab
str2 = xxy
Output: 1
Explanation: There are two different
charactersin aab and xxy, i.e a and b
with frequency 2and 1 respectively.

Example 2:
Input:
str1 = aab
str2 = xyz
Output: 0
Explanation: There are two different
charactersin aab but there are three
different charactersin xyz. So there
won't be one to one mapping between
str1 and str2.
Your Task:
You don't need to read input or print anything.Your task is to complete the function areIsomorphic() which takes the string str1 and string str2 as input parameter and  check if two strings are isomorphic. The function returns true if strings are isomorphic else it returns false.
Expected Time Complexity: O(|str1|+|str2|).
Expected Auxiliary Space: O(Number of different characters).
Note: |s| represents the length of string s.
Constraints:
1 <= |str1|, |str2| <= 2*104
+1
aryangarg19993 days ago
 bool areIsomorphic(string str1, string str2)
    {
        // We can map each character with the other ones and if that satisfies
        // the CONTINUE else break and return "false".
        
        int len1 = str1.length() , len2 = str2.length() ;
        
        if(len1 != len2)
        return false ;
        
        unordered_map<char, char>m1 ;
        unordered_map<char, char>m2 ;
        
        // 2 are there to cross verify the characters from the string ...
        
        for(int i=0; i<len1; i++)
        {
            char ch1 = str1[i] ;
            char ch2 = str2[i] ;
            
            if(m1.find(ch1) == m1.end() and m2.find(ch2) == m2.end())
            {
                m1[ch1] = ch2 ;
                m2[ch2] = ch1 ;
            }
            
            else if(m1.find(ch1) == m1.end() or m2.find(ch2) == m2.end())
            return false ;
            
            else
            {
                if(m1[ch1] == ch2 and m2[ch2] == ch1)
                continue ;
                
                else
                return false ;
            }
            
        }
        
        return true ;
        
        
    }
+3
avinav26112 weeks ago
Easy C++ Solution (0.03/1.6 sec)
 
0
mahesh_phutane2 weeks ago
//Simple java solution using hashing
class Solution
{
    //Function to check if two strings are isomorphic.
    public static boolean areIsomorphic(String str1,String str2)
    {
        if(str1.length()!=str2.length()) return false;
        
        int n= str1.length();
        Map<Character,Character> mp1 = new HashMap<>();
        Map<Character,Character> mp2 = new HashMap<>();
        
        for(int i = 0;i<n;i++){
            if(!mp1.containsKey(str1.charAt(i)) && !mp2.containsKey(str2.charAt(i))){
                mp1.put(str1.charAt(i),str2.charAt(i));
                mp2.put(str2.charAt(i),str1.charAt(i));
            }
            else if(mp1.containsKey(str1.charAt(i))){
                
                if((mp1.get(str1.charAt(i))!=str2.charAt(i))){
                return false;
             }
            }
            else if(mp2.containsKey(str2.charAt(i))){
                
                if((mp2.get(str2.charAt(i))!=str1.charAt(i))){
                return false;
             }
            }
        }
        return true;
    }
}
+2
sachinsingh42233 weeks ago
bool areIsomorphic(string str1, string str2)   {              // Your code here       if(str1.length()!=str2.length()){           return false;       }       int count1[26]={0};       int count2[26]={0};       for(int i=0;i<str1.length();i++){           count1[str1[i]-'a']++;           count2[str2[i]-'a']++;       }       for(int i=0;i<str1.length();i++){           if(count1[str1[i]-'a']==count2[str2[i]-'a']){               continue;           }           else{               return false;           }       }       return true;          }
 
0
kshitij14103 weeks ago
 bool areIsomorphic(string str1, string str2)   {              int n1=str1.size();       int n2=str2.size();       if(n1!=n2) return false;              int dp[MAX_CHARS];      for(int i=0;i<256;i++) dp[i]=-1;       int flag=0;       for(int i=0;i<n1;i++)       {           //not present in dp           if(dp[str1[i]]==-1)           {               dp[str1[i]]=str2[i];                          }           else{               //present in dp               int dpval=dp[str1[i]];                             if((dpval)!=str2[i])               {                   flag=1;                   break;               }           }                  }               int dp1[MAX_CHARS];       for(int i=0;i<256;i++) dp1[i]=-1;       int flag1=0;       for(int i=0;i<n1;i++)       {           //not present in dp           if(dp1[str2[i]]==-1)           {               dp1[str2[i]]=str1[i];                          }           else{               //present in dp               int dpval=dp1[str2[i]];                             if((dpval)!=str1[i])               {                   flag1=1;                   break;               }           }                  }       if(flag==1 || flag1==1) return false;       return true;   }
0
kishore1js17cs0474 weeks ago
One liner:
return len(set(zip(str1, str2))) == len(set(str1)) and len(set(zip(str2, str1))) == len(set(str2))
 
+1
manishmaheshwari81331 month ago
JAVA SOLUTION
TC: O(|str1|)logN
SC: O(Number of different characters)
class Solution
{
    //Function to check if two strings are isomorphic.
    public static boolean areIsomorphic(String str1,String str2)
    {
     if(str1.length()!=str2.length())return false;
        HashMap<Character,Character> map1=new HashMap<>();
        HashMap<Character,Boolean> map2=new HashMap<>();
        
        for(int i=0;i<str1.length();i++) {
        	char chr1=str1.charAt(i);
        	char chr2=str2.charAt(i);
        	
        	if(map1.containsKey(chr1)==true) {
        		if(map1.get(chr1)!=chr2) 
        			return false;
        	}else {
        		if(map2.containsKey(chr2)==true)return false;
        		else {
        			map1.put(chr1, chr2);
        			map2.put(chr2, true);
        		}
        	}
        }
        return true;
    }
}
0
zakarian17s1 month ago
bool areIsomorphic(string str1, string str2)
    {
        if(str1.length()!=str2.length()) return 0;
        map<char,int> s1,s2;
        for(int i=0;i<str1.length();i++){
            if((s1.find(str1[i])!=s1.end() && s2.find(str2[i])==s2.end())
            || (s1.find(str1[i])==s1.end() && s2.find(str2[i])!=s2.end())
            || (s1.find(str1[i])!=s1.end() && s1[str1[i]]!=s2[str2[i]]))
                     return 0;
            s1[str1[i]]=i;
            s2[str2[i]]=i;
        }
        if(s1.size()!=s2.size()) return 0;
        return 1;
    }
0
shashanksng201 month ago
//JAVA EASY SOLUTION
class Solution{   //Function to check if two strings are isomorphic.   public static boolean areIsomorphic(String str1,String str2)   {       // Your code here       HashMap<Character,Character> hmap=new HashMap<>();              HashMap<Character,Character> hmap1=new HashMap<>();              HashSet<Character> hs=new HashSet<>();       HashSet<Character> hs1=new HashSet<>();              for(int i=0;i<str1.length();i++)       {           hs.add(str1.charAt(i));       }              for(int j=0;j<str2.length();j++)       {           hs1.add(str2.charAt(j));       }             // System.out.println(hs.size() + " "  + hs1.size());       if(hs.size()!=hs1.size())       {           return false;       }                           for(int i=0,j=0;i<str1.length()  && j<str2.length();i++,j++)       {           if(!(hmap.containsKey(str1.charAt(i))))           {               hmap.put(str1.charAt(i),str2.charAt(j));                          }           else if(hmap.containsKey(str1.charAt(i)))           {               char c=hmap.get(str1.charAt(j));            //   System.out.println(c);               hmap.put(str1.charAt(i),str2.charAt(j));                              char nc=hmap.get(str1.charAt(j));              // System.out.println(nc);                                            if(c!=nc )               {                   return false;               }           }           // System.out.println(Arrays.asList(hmap));       }       return true;          }}
0
ciph3rcodes1 month ago
JAVA EASY SOLUTION (0.4 secs)
 
class Solution
{

   public static boolean areIsomorphic(String str1,String str2)
   {
     
       int l1=str1.length();
       int l2=str2.length();
       if(l1!=l2)
        return false;
       HashMap<Character,Character> hm1=new HashMap<>();
        HashMap<Character,Character> hm2=new HashMap<>();
         for(int i=0;i<l1;i++){
             char ch=str1.charAt(i);
             char ch2=str2.charAt(i);
             Character c1=hm1.get(ch);
             Character c2=hm2.get(ch2);
             if(hm1.get(ch)==null){
              
                 hm1.put(ch,ch2);
             }
             else{
                if(c1!=ch2)
                 return false;
             }
              if(hm2.get(ch2)==null){
              
                 hm2.put(ch2,ch);
             }
             else{
                if(c2!=ch)
                 return false;
             }
             
           
             
         }
         
         return true;
       
   }
}

We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.