Hashing · Medium
Isomorphic Strings
Solve it on DeVert Campus - free code runner
Problem
Given two strings s and t of equal length, determine whether they are isomorphic. Two strings are isomorphic if the characters in s can be replaced according to a consistent one-to-one mapping to obtain exactly t: every occurrence of a given character in s must map to the same character in t, and no two distinct characters in s may map to the same character in t.
Input and output
Input: The first line contains string s. The second line contains string t, with |t| = |s|.
Output: Print YES if s and t are isomorphic, otherwise print NO.
Example
Input: egg add Output: YES
Constraints
1 <= |s| = |t| <= 10^5. Both strings consist only of lowercase English letters.
Key observation
This is fundamentally about a strict ONE-TO-ONE (bijective) correspondence between characters, not just 'some consistent replacement rule' - the two-way hash map check is precisely what distinguishes true isomorphism from a weaker, one-directional pattern match.
Intuition
Check whether two equal-length strings follow a consistent, one-to-one character substitution pattern from one to the other.
Brute force: Try every possible one-to-one character mapping between the alphabets directly and check if applying it to s reproduces t exactly - this is combinatorially wasteful compared to building the mapping incrementally in a single pass.
Optimised: Maintaining BOTH forward (s to t) and backward (t to s) hash maps simultaneously, checked at every position in a single pass, correctly enforces the TRUE one-to-one requirement - checking only one direction would incorrectly accept cases where two different s characters both map to the same t character, which isn't genuine isomorphism.
Step by step
1. Scan both strings together, building a mapping from each character of s to its corresponding character of t.
2. A ONE-DIRECTIONAL map isn't enough - also track the REVERSE mapping (from t's characters back to s's), checking that no two different characters of s ever map to the SAME character of t.
3. If both mappings stay consistent throughout the entire scan, the strings are isomorphic.
Complexity
Time: O(n) - one single pass through both strings simultaneously, with O(1) hash map lookups at each position.
Space: O(alphabet size), for the two mapping hash maps.
Edge cases
Two identical strings are always isomorphic (each character maps to itself). Watch for cases where the reverse mapping is violated even though the forward mapping looks consistent.
Interview tip
Be ready to explain explicitly WHY checking only ONE direction of the mapping is insufficient - a common subtle bug is forgetting the reverse mapping check, which would wrongly accept strings like 'ab' and 'aa' as isomorphic.