Check if Two Strings Are Isomorphic
Implement isIsomorphic
Given two strings
s and t of the same length, return true if they're isomorphic — meaning the characters of s can be replaced, one-for-one and consistently, to get exactly t. No two characters may map to the same character, but a character may map to itself.
Comparing every pair of positions directly confirms consistency but costs O(n²). The faster approach walks both strings together while tracking the mapping both ways — s-to-t and t-to-s — in two hash maps. Checking both directions at every step is what catches both kinds of broken mapping in a single pass.
Example 1:
Input: s = "egg", t = "add"
Output: true
Example 2:
Input: s = "foo", t = "bar"
Output: false
Example 3:
Input: s = "ab", t = "aa"
Output: false
+ 3 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 5 × 10⁴ - ●
t.length == s.length - ●
s and t consist of lowercase English letters
s =
egg
t =
add