Problem 205

Abstract / Summary

Check if characters in one string can be replaced to get the other while keeping the mapping consistent both ways.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 0205.py

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        s2t = { }
        t2s = { }
        for i in range(len(s)):
            if s[i] in s2t:
                if s2t[s[i]] != t[i]:
                    return False
            else:
                s2t[s[i]] = t[i]

            t2s[t[i]] = s[i]

        return len(s2t.keys()) == len(t2s.keys())
14 lines | 381 bytes | submitted August 18, 2023 | GitHub   tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 49% (4+ million submissions).

Typical patterns to solve this problem:
  • Hash Table
  • String
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation determines whether two strings s and t are isomorphic. Two strings are isomorphic when characters in s can be replaced to obtain t while preserving the order of characters, and no two different characters from s map to the same character in t. The algorithm builds two dictionaries that record the forward mapping (s → t) and the reverse mapping (t → s). After processing all positions, it validates that the number of distinct mappings in both directions is identical, which guarantees a bijective relationship.

Key Steps

Initialization of Mapping Containers

The solution creates two empty dictionaries to store character correspondences.

s2t = {}
t2s = {}

These structures enable constant-time look-ups for previously seen characters, which is essential for detecting conflicting mappings early.

Iteration Over Characters

A single loop traverses the indices of the input strings. The loop length equals the length of s, which is assumed to be the same as t for a valid isomorphism check.

for i in range(len(s)):

Processing characters by index allows simultaneous access to the paired characters s[i] and t[i].

Forward Mapping Validation

Inside the loop, the code first checks whether the current character from s already has an entry in the forward dictionary. If it does, the stored target character must match the current character from t; otherwise the strings cannot be isomorphic and the function returns False.

if s[i] in s2t:
    if s2t[s[i]] != t[i]:
        return False
else:
    s2t[s[i]] = t[i]

This step ensures that a single source character never maps to two different target characters.

Reverse Mapping Update

Regardless of whether the forward mapping existed, the reverse dictionary is updated with the current pair. This unconditional assignment records the most recent source character for each target character.

t2s[t[i]] = s[i]

Because the forward check already guarantees consistency, overwriting an existing entry in t2s does not introduce contradictions.

Final Consistency Check

After the loop finishes, the function compares the number of distinct keys in both dictionaries. Equality of these counts confirms that the mapping is one-to-one in both directions.

return len(s2t.keys()) == len(t2s.keys())

If the counts differ, it would indicate that some target character was associated with multiple source characters, violating the isomorphism condition.

Edge Cases Handled

The algorithm gracefully handles strings containing repeated characters. When a character repeats in s, the forward dictionary already contains an entry, and the code verifies that the corresponding character in t matches the stored mapping. This prevents false positives where a repeated source character could incorrectly map to different target characters.

When t contains repeated characters, the reverse dictionary is updated each time. Because the forward validation already ensures a unique mapping from each source character, the final key-count comparison catches any scenario where two different source characters map to the same target character.

Empty strings are also covered: the loop body never executes, both dictionaries remain empty, and the final comparison yields True, correctly indicating that two empty strings are trivially isomorphic.

Performance Optimizations Observed

The solution uses two hash tables for constant-time insertion and lookup, eliminating the need for nested loops or repeated scans of the strings. By performing the forward consistency check before updating the reverse dictionary, the algorithm avoids unnecessary work when a conflict is detected early, allowing an immediate return. The final equality test on dictionary key counts is a single O(1) operation after the linear pass, avoiding any additional traversal of the strings. These choices keep the overall processing time proportional to the length of the input strings while using only a modest amount of auxiliary memory for the two dictionaries.

written by openai gpt

ELI5 - Simplified Explanation

Imagine you have two rows of colorful building blocks and a special magic notebook. The goal is to see if these two rows are wearing the exact same patterns, even if the colors are different.

First, empty out two pages in the notebook. One page is for remembering how colors in the first row match up to colors in the second row, and the other page is for tracking the reverse.

Now, walk along the rows one step at a time. Pick up a block from the first row and a block from the second row at the same spot. Check the notebook to see if a secret code for the first color has already been written down. If it is already there, make sure it matches the new block. If it is not there, write it down so the notebook remembers the pair.

Do this for every single block in both rows. Once finished, count how many unique color rules were saved in both pages of the notebook. If the number of rules on both sides matches, it means the pattern is the same.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 26 | median = 7 | μ = 6.85 | σ = 1.43

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java C# Rust Go TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JS
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, C#, Go, Java, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
aylei Rust
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
everthis JavaScript
fartem Ruby
fengvyi C++
fpdjsns C++
gaosq0604 Python
gouthampradhan Java
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C++
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
muhammadfarhankt Go
pruthvikp Python
qiyuangong Python
ruoru Rust
shreymehul C#
sonugiri1043 C++
suxrobGM C#
varunu28 Java
vli02 C
vthwang Java
XiaotaoGuo C++
yuanliu666 Kotlin
YuriSpiridonov Python
zfang399 C++
59 links | 43 authors | 11 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Isomorphic Strings - Leetcode 205 - Python'
NeetCode 11 mins
Isomorphic Strings - Leetcode 205 - Python
YouTube video 'Isomorphic Strings | Simple Thought Process | Leetcode 205| LinkedIn | codestorywithMIK'
codestorywithMIK 20 mins
Isomorphic Strings | Simple Thought Process | Leetcode 205| LinkedIn | codestorywithMIK
YouTube video 'Isomorphic Strings | Leetcode 205 | C++ | Python | Code + Approach | Hashing'
Ayushi Sharma 14 mins
Isomorphic Strings | Leetcode 205 | C++ | Python | Code + Approach | Hashing
YouTube video '3. Isomorphic Strings | Strings - Easy | #LearnDSA | Leetcode 205'
Ayushi Sharma 16 mins
3. Isomorphic Strings | Strings - Easy | #LearnDSA | Leetcode 205
YouTube video '205. Isomorphic Strings || Java || Leetcode || Hindi'
Coding Sphere 13 mins
205. Isomorphic Strings || Java || Leetcode || Hindi
YouTube video '205. Isomorphic Strings | Hash Map | Strings'
Aryan Mittal 16 mins
205. Isomorphic Strings | Hash Map | Strings
YouTube video 'Master LeetCode 205 with the Best Solution! | Isomorphic Strings'
Engineering Digest 14 mins
Master LeetCode 205 with the Best Solution! | Isomorphic Strings
YouTube video '205. Isomorphic Strings | Leetcode Easy | Hash Table Series | LEETCODE'
code Explainer 8 mins
205. Isomorphic Strings | Leetcode Easy | Hash Table Series | LEETCODE
YouTube video 'Leetcode 205. Isomorphic Strings [Java]'
if else statement 7 mins
Leetcode 205. Isomorphic Strings [Java]
YouTube video 'Isomorphic Strings | LeetCode 205 | Theory + Python'
Sai Anish Malla 11 mins
Isomorphic Strings | LeetCode 205 | Theory + Python
YouTube video 'Isomorphic Strings (Java) | Leetcode 205 | July Coding Challenge Day 12'
Puru Arora 10 mins
Isomorphic Strings (Java) | Leetcode 205 | July Coding Challenge Day 12
YouTube video 'Isomorphic Strings | Leetcode 205 | Live coding session'
Coding Decoded 9 mins
Isomorphic Strings | Leetcode 205 | Live coding session
YouTube video 'Leetcode | 205. Isomorphic Strings | Easy | Java Solution'
Developer Docs 8 mins
Leetcode | 205. Isomorphic Strings | Easy | Java Solution
YouTube video 'LeetCode 205 - Isomorphic Strings | Java Solution [EASY]'
Code with Carter 12 mins
LeetCode 205 - Isomorphic Strings | Java Solution [EASY]
YouTube video '205. Isomorphic Strings | April | Java | C++'
Mayur Programming Club 26 mins
205. Isomorphic Strings | April | Java | C++
YouTube video 'Isomorphic Strings - Leetcode 205 | Easy HashMap Solution Explained'
Web Coder Abhishek 6 mins
Isomorphic Strings - Leetcode 205 | Easy HashMap Solution Explained
YouTube video 'Leetcode 205: Isomorphic Strings in Telugu | Bi-Directional, Pattern Matching | srkcodes'
Srk Codes 9 mins
Leetcode 205: Isomorphic Strings in Telugu | Bi-Directional, Pattern Matching | srkcodes
YouTube video 'Isomorphic Strings (LeetCode 205) (Time- O(N))'
CodeWithARB 7 mins
Isomorphic Strings (LeetCode 205) (Time- O(N))
YouTube video 'Isomorphic Strings | LeetCode 205 | Coders Camp'
Coders Camp 7 mins
Isomorphic Strings | LeetCode 205 | Coders Camp
YouTube video 'Daily Leetcode #468: Jul 12, 2021 - 205. Isomorphic Strings'
Programming Live with Larry 6 mins
Daily Leetcode #468: Jul 12, 2021 - 205. Isomorphic Strings
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

3 easy 7 medium 2 hard
13 solutions   August 18, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality