205. Isomorphic Strings LeetCode Solution

In this guide, you will get 205. Isomorphic Strings LeetCode Solution with the best time and space complexity. The solution to Isomorphic Strings problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Isomorphic Strings solution in C++
  4. Isomorphic Strings solution in Java
  5. Isomorphic Strings solution in Python
  6. Additional Resources
205. Isomorphic Strings LeetCode Solution image

Problem Statement of Isomorphic Strings

Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.

Example 1:

Input: s = “egg”, t = “add”
Output: true
Explanation:
The strings s and t can be made identical by:

Mapping ‘e’ to ‘a’.
Mapping ‘g’ to ‘d’.

Example 2:

Input: s = “foo”, t = “bar”
Output: false
Explanation:
The strings s and t can not be made identical as ‘o’ needs to be mapped to both ‘a’ and ‘r’.

Example 3:

Input: s = “paper”, t = “title”
Output: true

Constraints:

1 <= s.length <= 5 * 104
t.length == s.length
s and t consist of any valid ascii character.

Complexity Analysis

  • Time Complexity: O(n)
  • Space Complexity: O(128) = O(1)

205. Isomorphic Strings LeetCode Solution in C++

class Solution {
 public:
  bool isIsomorphic(string s, string t) {
    vector<int> charToIndex_s(128);
    vector<int> charToIndex_t(128);

    for (int i = 0; i < s.length(); ++i) {
      if (charToIndex_s[s[i]] != charToIndex_t[t[i]])
        return false;
      charToIndex_s[s[i]] = i + 1;
      charToIndex_t[t[i]] = i + 1;
    }

    return true;
  }
};
/* code provided by PROGIEZ */

205. Isomorphic Strings LeetCode Solution in Java

class Solution {
  public boolean isIsomorphic(String s, String t) {
    Map<Character, Integer> charToIndex_s = new HashMap<>();
    Map<Character, Integer> charToIndex_t = new HashMap<>();

    for (Integer i = 0; i < s.length(); ++i)
      if (charToIndex_s.put(s.charAt(i), i) != charToIndex_t.put(t.charAt(i), i))
        return false;

    return true;
  }
}
// code provided by PROGIEZ

205. Isomorphic Strings LeetCode Solution in Python

class Solution:
  def isIsomorphic(self, s: str, t: str) -> bool:
    return [*map(s.index, s)] == [*map(t.index, t)]
# code by PROGIEZ

Additional Resources

See also  594. Longest Harmonious Subsequence LeetCode Solution

Happy Coding! Keep following PROGIEZ for more updates and solutions.