205. Isomorphic Strings
Easy
|
Hash Table
String
|
Solved: Mar 15, 2026
View on LeetCode →
View on NeetCode →
Complexity Analysis
Time Complexity: O(n log n)
Space Complexity: O(n)
Problem Description
Given two strings s and t, determine if they are isomorphic.
Two strings s and t are isomorphic if the characters in s can be replaced to get t.
All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself.
Example 1:
Input: s = "egg", t = "add"
Output: true
Explanation:
The strings s and t can be made identical by:
Mapping 'e' to 'a'.
Mapping 'g' to 'd'.
Example 2:
Input: s = "f11", t = "b23"
Output: false
Explanation:
The strings s and t can not be made identical as '1' needs to be mapped to both '2' and '3'.
Example 3:
Input: s = "paper", t = "title"
Output: true
Constraints:
1 <= s.length <= 5 * 10^4t.length == s.lengthsandtconsist of any valid ascii character.
Approach
Use two TreeMaps to count the frequencies of characters in both strings. Then, iterate through the strings again to ensure that at each index i, the character in string s has the same total frequency as the character in string t.
Solution
class Solution {
public boolean isIsomorphic(String s, String t) {
if(s.length()!=t.length()){
return false;
}
int n = s.length();
TreeMap<Character, Integer> hashs = new TreeMap<>();
TreeMap<Character, Integer> hasht = new TreeMap<>();
for(int i=0;i<n;i++){
hashs.put(s.charAt(i), hashs.getOrDefault(s.charAt(i), 0)+1);
hasht.put(t.charAt(i), hasht.getOrDefault(t.charAt(i), 0)+1);
}
for(int i=0;i<n;i++){
if(hashs.get(s.charAt(i))!=hasht.get(t.charAt(i))){
return false;
}
}
return true;
}
}