Determining isomorphic strings JavaScript

Two strings are isomorphic if characters in one string can be mapped to characters in another string while preserving the structure. Each character must map to exactly one character, and no two characters can map to the same character.

Understanding Isomorphic Strings

For strings to be isomorphic:

  • They must have the same length
  • Characters at the same positions must follow a consistent mapping pattern
  • The mapping must be bijective (one-to-one)

Example

const str1 = 'egg';
const str2 = 'add';

// Check if strings are isomorphic
const isIsomorphic = (str1 = '', str2 = '') => {
    if (str1.length !== str2.length) {
        return false;
    }
    
    for (let i = 0; i 

true
true
false

How It Works

The algorithm compares the first occurrence index of each character in both strings. If characters appear at the same relative positions in both strings, they maintain the isomorphic property.

Alternative Approach Using Maps

const isIsomorphicWithMap = (str1, str2) => {
    if (str1.length !== str2.length) return false;
    
    const mapStr1ToStr2 = new Map();
    const mapStr2ToStr1 = new Map();
    
    for (let i = 0; i 

true
false

Comparison

Method Time Complexity Space Complexity Readability
indexOf() approach O(n²) O(1) Simple
Map approach O(n) O(n) More explicit

Conclusion

Isomorphic strings maintain consistent character mapping patterns. The indexOf() method provides a simple solution, while the Map approach offers better time complexity for larger strings.

Updated on: 2026-03-15T23:19:00+05:30

843 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements