Open In App

POTD Solutions | 11 Nov’ 23 | Isomorphic Strings

Last Updated : 22 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

View all POTD Solutions

Welcome to the daily solutions of our PROBLEM OF THE DAY (POTD). We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of String but will also help you build up problem-solving skills.

11th-nov

POTD Solution 11 November 2023

We recommend you to try this problem on our GeeksforGeeks Practice portal first, and maintain your streak to earn Geeksbits and other exciting prizes, before moving towards the solution.

POTD 11 November: Isomorphic Strings

Given two strings ‘str1‘ and ‘str2‘, check if these two strings are isomorphic to each other.

If the characters in str1 can be changed to get str2, then two strings, str1 and str2, are isomorphic. A character must be completely swapped out for another character while maintaining the order of the characters. A character may map to itself, but no two characters may map to the same character.

Example:

Input:  str1 = “aab”, str2 = “xxy”
Output: True
Explanation: ‘a’ is mapped to ‘x’ and ‘b’ is mapped to ‘y’.

Input:  str1 = “aab”, str2 = “xyz”
Output: False
Explanation: One occurrence of ‘a’ in str1 has ‘x’ in str2 and other occurrence of ‘a’ has ‘y’.

Isomorphic Strings using Hashmap:

The idea is to store map the character and check whether the mapping is correct or not.

Step-by-step approach:

  • Create a hashmap of (char, char) to store the mapping of str1 and str2.
  • Now traverse on the string and check whether the current character is present in the Hashmap.
    • If it is present then the character that is mapped is there at the ith index or not.
    • Else check if str2[i] is not present in the key then add the new mapping.
    • Else return false.

Below is the implementation of the above approach:

C++




class Solution
{
    public:
    //Function to check if two strings are isomorphic.
    bool areIsomorphic(string str1, string str2)
    {
         int m = str1.length(), n = str2.length();
          
        if (m != n)
            return false;
          
        //using a boolean array to mark visited characters in str2.
        bool marked[MAX_CHARS] = {false};
          
        //using map to store mapping of every character from str1 to
        //that of str2. Initializing all entries of map as -1.
        int map[MAX_CHARS];
        memset(map, -1, sizeof(map));
          
         
        for (int i = 0; i < n; i++)
        {
            //if current character of str1 is seen first time in map.
            if (map[str1[i]] == -1)
            {
                //if current character of str2 is already
                //seen, one to one mapping is not possible.
                if (marked[str2[i]] == true)
                    return false;
                  
                //marking current character of str2 as visited.
                marked[str2[i]] = true;
                  
                //storing mapping of current characters.
                map[str1[i]] = str2[i];
            }
              
            //if this isn't first appearance of current character in str1 then
            //checking if previous appearance mapped to same character of str2.
            else if (map[str1[i]] != str2[i])
                return false;
        }
        return true;
    }
};


Java




class Solution
{
    //Function to check if two strings are isomorphic.
    public static boolean areIsomorphic(String str1,String str2)
    {
         
           int m = str1.length();
        int n = str2.length();
  
        if (m != n) {
            return false;
        }
  
        // Using a boolean array to mark visited characters in str2.
        boolean[] marked = new boolean[256];
  
        // Using a map to store mapping of every character from str1 to that of str2.
        // Initializing all entries of map as -1.
        Map<Character, Character> map = new HashMap<>();
  
        for (int i = 0; i < n; i++) {
            // If current character of str1 is seen first time in map.
            if (!map.containsKey(str1.charAt(i))) {
                // If current character of str2 is already seen,
                // one-to-one mapping is not possible.
                if (marked[str2.charAt(i)]) {
                    return false;
                }
  
                // Marking current character of str2 as visited.
                marked[str2.charAt(i)] = true;
  
                // Storing mapping of current characters.
                map.put(str1.charAt(i), str2.charAt(i));
            }
  
            // If this isn't the first appearance of the current character in str1,
            // then checking if the previous appearance mapped to the same character of str2.
            else if (map.get(str1.charAt(i)) != str2.charAt(i)) {
                return false;
            }
        }
  
        return true;
          
    }
}


Python3




class Solution:
      
    #Function to check if two strings are isomorphic.
    def areIsomorphic(self,str1,str2):
        m = len(str1)
        n = len(str2)
  
        if m != n:
            return False
  
        # Using a set to mark visited characters in str2.
        marked = set()
  
        # Using a dictionary to store mapping of every character from str1 to that of str2.
        # Initializing all entries of the dictionary as None.
        mapping = {}
  
        for i in range(n):
            # If current character of str1 is seen first time in mapping.
            if str1[i] not in mapping:
                # If current character of str2 is already seen,
                # one-to-one mapping is not possible.
                if str2[i] in marked:
                    return False
  
                # Marking current character of str2 as visited.
                marked.add(str2[i])
  
                # Storing mapping of current characters.
                mapping[str1[i]] = str2[i]
  
            # If this isn't the first appearance of the current character in str1,
            # then checking if the previous appearance mapped to the same character of str2.
            elif mapping[str1[i]] != str2[i]:
                return False
  
        return True


Time Complexity: O(N) i.e. O(|N| + |N|), Traversing over the string of size N, where N is the length of the string.
Auxiliary Space: O(1)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads