LeetCode 205: Isomorphic Strings Solution

Master LeetCode problem 205 (Isomorphic Strings), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

205. Isomorphic Strings

Problem Explanation

Explanation:

To solve this problem, we can iterate through each character in both strings s and t simultaneously. At each step, we can maintain a mapping of characters from s to t and vice versa. If a character from s has not been mapped to any character in t and vice versa, we can create a mapping for them. If a character from s has already been mapped to a different character in t, or vice versa, then the strings are not isomorphic.

We need to check both mappings to ensure that the transformation is consistent in both directions. By keeping track of the mappings in two hash maps, we can efficiently determine if the strings are isomorphic.

  • Time complexity: O(n), where n is the length of the input strings s and t.
  • Space complexity: O(n) to store the mappings in the hash maps.

Solution Code

class Solution {
    public boolean isIsomorphic(String s, String t) {
        if(s.length() != t.length()) {
            return false;
        }
        
        Map<Character, Character> sMap = new HashMap<>();
        Map<Character, Character> tMap = new HashMap<>();
        
        for(int i = 0; i < s.length(); i++) {
            char sChar = s.charAt(i);
            char tChar = t.charAt(i);
            
            if(sMap.containsKey(sChar)) {
                if(sMap.get(sChar) != tChar) {
                    return false;
                }
            } else {
                sMap.put(sChar, tChar);
            }
            
            if(tMap.containsKey(tChar)) {
                if(tMap.get(tChar) != sChar) {
                    return false;
                }
            } else {
                tMap.put(tChar, sChar);
            }
        }
        
        return true;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 205 (Isomorphic Strings)?

This page provides optimized solutions for LeetCode problem 205 (Isomorphic Strings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 205 (Isomorphic Strings)?

The time complexity for LeetCode 205 (Isomorphic Strings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 205 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 205 in Java, C++, or Python.

Back to LeetCode Solutions