BudiBadu Logo

Isomorphic Strings

Hash Table Easy 1 views
Like0

Ever wondered if two words follow the exact same "blueprint"? That’s the core of Isomorphic Strings! Two strings are isomorphic if the characters in the first string can be replaced to get the second string, following a strict one-to-one character mapping. Think of it like a secret code: if 'e' maps to 'a' in one spot, it must map to 'a' everywhere else.

The "secret sauce" here is using Two Hash Maps (or one map and a set) to track the relationship in both directions. You need to ensure that no two characters from the first word map to the same character in the second word, and vice versa. It’s like a high-stakes matching game where every character must have exactly one unique partner.

This approach runs in linear time O(n), making it incredibly fast. It’s the gold standard for pattern-matching problems where the character structure matters more than the actual letters themselves.

For text and token tasks, be precise with index movement and substring boundaries. Most hidden failures come from partial-match handling and boundary cuts, so keep comparisons explicit and avoid assumptions about implicit separators or formatting not guaranteed by the input contract.

Examples

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 - Budibadu
Recommendation Algorithm Flow for Isomorphic Strings - Budibadu

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;
    }
}