Isomorphic Strings
Easy · Arrays & Hashing · Hash Table · String
Problem
You are given two strings s and t of the same length. They are isomorphic when the characters of s can be replaced to turn s into t under one consistent rule:
- every occurrence of a character is replaced by the same character,
- the order of the characters is kept, and
- no two different characters are replaced by the same character (a character may stay as itself).
Return true if s and t are isomorphic, otherwise false.
Examples
Input: s = "noon", t = "deed" Output: true
n becomes d and o becomes e everywhere, and no two letters share an image.
Input: s = "abc", t = "xyx" Output: false
a and c would both have to become x.
Input: s = "aa", t = "ab" Output: false
The same a would have to become a at one place and b at another.
Constraints
- 1 <= len(s) <= 5 · 10^4
- len(t) == len(s)
- s and t contain printable ASCII characters
Approaches
- Baseline: compare every pair of positions — time O(n²), space O(1)
Follow-up
Another way to say it: two strings are isomorphic when they have the same shape, where the shape replaces each character by the index of its first appearance ("paper" and "title" both become 0,1,0,3,4). Comparing shapes extends directly to grouping many strings by pattern, as the second use case below does.
Related problems
Start free on Cariara · Coding problems · System design studio