Skip to main content

Isomorphic Strings

LeetCode 205 | Difficulty: Easy​

Easy

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^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?

When to use

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.

When to use

Anagram detection, palindrome checking, string transformation, pattern matching.


Solutions​

Solution 1: C# (Best: 139 ms)​

MetricValue
Runtime139 ms
Memory37.6 MB
Date2022-02-16
Solution
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​

ApproachTimeSpace
Hash Map$O(n)$$O(n)$

Interview Tips​

Key Points
  • 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.