Isomorphic Strings
easy
strings
hashmap
Two strings s and t are isomorphic if the characters of s can be replaced to get t while preserving order.
Every occurrence of a character must map to the same character, and no two characters may map to the same character. A character may map to itself.
Input / output
- Input:
s: string,t: string - Output:
boolean
Examples
s = "egg",t = "add"returnstrue(e->a,g->d).s = "foo",t = "bar"returnsfalse(owould map to bothaandr).s = "paper",t = "title"returnstrue.
Constraints
0 <= s.length == t.length <= 50000sandtconsist of any Unicode characters (ASCII in the tests).
Edge cases
- Two empty strings are isomorphic.
- Mapping must be one-to-one in both directions, so
"badc"and"baba"are not isomorphic.
Target complexity
- Aim for
O(n)time andO(1)extra space (bounded alphabet).
Hints
- Walk both strings together and remember the pairing seen for each character.
- You need two maps: one from
stotand one fromttos.
Follow-up How does this differ from checking whether the two strings follow the same repetition pattern (word pattern)?
Examples
Example 1
Input: s = "egg", t = "add"
Output: true
Example 2
Input: s = "foo", t = "bar"
Output: false
Example 3
Input: s = "paper", t = "title"
Output: true
🔒 5 hidden
Running will execute all 8 cases, including 5 hidden ones.