Isomorphic Strings
LeetCode 205 | Difficulty: Easyβ
EasyProblem 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^4`
- `t.length == s.length`
- `s` and `t` consist of any valid ascii character.
Topics: Hash Table, String
Approachβ
Hash Mapβ
Use a hash map for O(1) average lookups. Store seen values, frequencies, or indices. The key question: what should I store as key, and what as value?
Need fast lookups, counting frequencies, finding complements/pairs.
String Processingβ
Consider character frequency counts, two-pointer approaches, or building strings efficiently. For pattern matching, think about KMP or rolling hash. For palindromes, expand from center or use DP.
Anagram detection, palindrome checking, string transformation, pattern matching.
Solutionsβ
Solution 1: C# (Best: 139 ms)β
| Metric | Value |
|---|---|
| Runtime | 139 ms |
| Memory | 37.6 MB |
| Date | 2022-02-16 |
public class Solution {
public bool IsIsomorphic(string s, string t) {
Dictionary<char,char> keyValuePairs = new Dictionary<char,char>();
for (int i = 0; i < s.Length; i++)
{
if(keyValuePairs.ContainsKey(s[i]))
{
if (keyValuePairs[s[i]] == t[i])
continue;
else
return false;
}
if (keyValuePairs.ContainsValue(t[i]))
return false;
keyValuePairs.Add(s[i], t[i]);
}
return true;
}
}
Complexity Analysisβ
| Approach | Time | Space |
|---|---|---|
| Hash Map | $O(n)$ | $O(n)$ |
Interview Tipsβ
- Start by clarifying edge cases: empty input, single element, all duplicates.
- Hash map gives O(1) lookup β think about what to use as key vs value.