![]() |
VOOZH | about |
Given two strings s1 and s2 of equal length, consisting only of lowercase English letters, determine if they are isomorphic.
Two strings are isomorphic if characters in s1 can be replaced to get s2 such that:
Examples:
Input: s1 = "aab", s2 = "xxy"
Output: true
Explanation: Each character in s1 can be consistently mapped to a unique character in s2 (a → x, b → y).Input: s1 = "aab", s2 = "xyz"
Output: false
Explanation: Same character 'a' in s1 maps to two different characters 'x' and 'y' in s2.Input: s1 = "abc", s2 = "xxz"
Output: false
Explanation: Two different characters 'a' and 'b' in s1 maps with same character 'x' in s2.
Table of Content
A simple Solution is to consider every character of 's1' and check if all occurrences of it map to the same character in 's2'.
true
The idea is based on the fact that all occurrences of two characters should be at same index. We mainly store the first index of every character and for remaining occurrences, we check if they appear at same first index too.
We mainly use two maps m1 and m2 to store characters as keys and their first indexes as values.
true
Time Complexity: O(n) We traverse both strings once, and all hash map operations (insert and lookup) take constant time on average.
Auxiliary Space: O(1) Since the strings contain only lowercase English letters, the maximum size of each hash map is bounded by 26, making it constant space.
We avoid language-specific hash overhead by using fixed-size arrays, leveraging the 26-letter lowercase alphabet. Each character is mapped to an index (
'a'→ 0, ...,'z'→ 25) for constant-time access. One array stores the character mappings, while another tracks if a character in the second string is already used — ensuring a one-to-one correspondence.
true
The idea is to store mapping of characters from s1 to s2 in a map and already seen characters of s2 in a set.
Step by Step Implementations:
true