Isomorphic Strings (LeetCode 205): Solution and Explanation

Easy
Hash Table
String

Two strings of equal length are isomorphic when you can rename the characters of the first to get the second, using a consistent rule where each character always maps to the same partner and no two characters share a partner. Given s and t, decide whether such a renaming exists.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Start with the definition. Every occurrence of a character in s must turn into the same character in t, so if 'p' becomes 't' once, it must become 't' everywhere. A natural first attempt is a single dictionary from characters of s to characters of t: walk the strings in parallel, record each pairing, and fail if a character of s shows up paired with something new.

That single map catches half the rule but misses the other half. Consider s = "badc" and t = "baba". The map would happily record b to b, a to a, d to b and c to a, and every character of s is consistent. Yet both 'b' and 'd' map to 'b', which means the renaming is not reversible, and the strings are not isomorphic. The relationship has to be a one-to-one correspondence, so you need to check consistency in both directions.

The clean fix is a second dictionary from t back to s. For each pair of characters, both maps must either have no entry yet or already agree with the current pair. If either map disagrees, return False immediately. If you get through the whole string, the pairing is consistent forward and backward, which is exactly what isomorphic means. Each pair is checked in constant time, so the whole thing is a single linear pass.

Approach: Two hash maps for a bijection

  1. If s and t differ in length, return False, since no character-for-character mapping can exist.
  2. Create two empty dictionaries: s_to_t for the forward mapping and t_to_s for the reverse mapping.
  3. Iterate over the characters in pairs with zip(s, t), calling them c1 and c2.
  4. If c1 already maps to something other than c2, return False because one source character would need two targets.
  5. If c2 already maps back to something other than c1, return False because two source characters would share a target.
  6. Record s_to_t[c1] = c2 and t_to_s[c2] = c1, then continue. If the loop finishes, return True.

Step-by-step example

s = "paper", t = "title"
  1. Pair ('p', 't'): neither map has an entry, so record p to t and t to p.
  2. Pair ('a', 'i'): both are new, so record a to i and i to a.
  3. Pair ('p', 't'): s_to_t['p'] is 't' and t_to_s['t'] is 'p', so both agree and nothing changes.
  4. Pair ('e', 'l'): both are new, so record e to l and l to e. Pair ('r', 'e'): both are new, so record r to e and e to r in the reverse map.
  5. The loop ends without a conflict, so the function returns True. By contrast, for s = "foo" and t = "bar", the third pair ('o', 'r') fails because 'o' already maps to 'a'.

Code: Python, Java, C++

1class Solution:
2    def isIsomorphic(self, s: str, t: str) -> bool:
3        if len(s) != len(t):
4            return False
5
6        s_to_t = {}
7        t_to_s = {}
8
9        for c1, c2 in zip(s, t):
10            if c1 in s_to_t and s_to_t[c1] != c2:
11                return False
12            if c2 in t_to_s and t_to_s[c2] != c1:
13                return False
14            s_to_t[c1] = c2
15            t_to_s[c2] = c1
16
17        return True

Time and space complexity

Time

O(n)

The loop visits each of the n character pairs once, and every dictionary lookup and insert takes constant time on average.

Space

O(k)

Each map holds at most one entry per distinct character, so space is bounded by the alphabet size k. With ASCII input that is at most 256 entries per map, which many people describe as O(1).

Other approaches

First-occurrence index pattern (time O(n), space O(n))

Transform each string into a list where every character is replaced by the index of its first occurrence, so "paper" becomes [0, 1, 0, 3, 4] and "title" becomes [0, 1, 0, 3, 4]. Two strings are isomorphic exactly when these patterns are equal. It avoids reasoning about two maps and generalizes well to grouping many strings by shape.

Last-seen position arrays (time O(n), space O(k))

Keep two fixed-size arrays indexed by character code that store the last position where each character appeared. At each index, the stored positions for s[i] and t[i] must be equal; then update both to i + 1. This uses plain arrays instead of hash maps and is often the fastest in Java and C++.

Common mistakes

  • Checking only the forward mapping. Inputs like "badc" and "baba" pass a one-way check even though two characters collapse into one.
  • Assuming characters are lowercase letters and using an array of size 26. The input can contain any ASCII character, including digits and punctuation.
  • Comparing sorted character frequency counts. Equal frequencies are necessary but not sufficient, because the positions of repeated characters must line up too.
  • In the position-array variant, initializing positions to 0 and storing i instead of i + 1, which makes the first index indistinguishable from never seen.

Frequently asked questions

Why do you need two hash maps for Isomorphic Strings?

One map only guarantees that each character of s has a single target. The second map guarantees that no two characters of s share a target. Together they enforce a one-to-one mapping.

Can a character map to itself?

Yes. The mapping is any consistent renaming, and keeping a character unchanged is allowed. For example, "ab" and "ac" are isomorphic with a mapping to a and b mapping to c.

How is this different from Word Pattern?

Word Pattern applies the same two-way mapping idea, but between characters of a pattern and whole words in a sentence. The algorithm is the same, with words split out first.