Code Logo

Isomorphic Strings

Published at16 Mar 2026
Easy 12 views
Like0

Two strings are isomorphic when the character pattern in one string can be matched to the character pattern in the other string with a consistent one-to-one mapping.

That means if a character in the first string appears again later, it must map to the same character again in the second string. It also means two different characters from the first string are not allowed to collapse into the same character in the second string.

For example, "egg" and "add" are isomorphic because e -> a and g -> d stay consistent across the whole string. But "foo" and "bar" are not isomorphic because the repeated o would need to map inconsistently.

So the task is to check whether one stable one-to-one character mapping can explain every position in both strings.

Example Input & Output

Example 1
Input
s = "egg", t = "add"
Output
true
Explanation

e->a and g->d is consistent.

Example 2
Input
s = "foo", t = "bar"
Output
false
Explanation

o cannot map to both a and r.

Example 3
Input
s = "paper", t = "title"
Output
true
Explanation

A consistent one-to-one mapping exists.

Algorithm Flow

Recommendation Algorithm Flow for Isomorphic Strings

Solution Approach

Check if two strings s and t are isomorphic, meaning characters in s can be replaced to get t while preserving the character mapping. Each character must map to exactly one other character, and no two characters can map to the same character. Use two hash maps tracking s-to-t and t-to-s mappings.

function isIsomorphic(s, t) {
  var sMap = {}, tMap = {};
  for (var i = 0; i < s.length; i++) {
    if (!sMap[s[i]] && !tMap[t[i]]) { sMap[s[i]] = t[i]; tMap[t[i]] = s[i]; }
    else if (sMap[s[i]] !== t[i] || tMap[t[i]] !== s[i]) return false;
  }
  return true;
}

Both direction maps ensure the mapping is a bijection. When a new character pair is encountered, both maps are updated. Any conflict with an existing mapping returns false.

Time complexity is O(n), space complexity is O(k).

Best Answers

java
import java.util.*;
class Solution {
    public boolean isomorphic_strings(String s, String t) {
        if (s.length() != t.length()) return false;
        Map<Character, Character> st = new HashMap<>();
        Map<Character, Character> ts = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            char a = s.charAt(i), b = t.charAt(i);
            if (st.containsKey(a) && st.get(a) != b) return false;
            if (ts.containsKey(b) && ts.get(b) != a) return false;
            st.put(a, b);
            ts.put(b, a);
        }
        return true;
    }
}