How to check if two strings are isomorphic in JavaScript

2 Answers

0 votes
// Two strings are isomorphic if characters in one can be replaced to get the other, 
// while preserving the order.

function areIsomorphic(s, t) {
  if (s.length !== t.length) return false;

  const mapST = new Map();
  const mapTS = new Map();

  for (let i = 0; i < s.length; i++) {
    const c1 = s[i];
    const c2 = t[i];

    // Check mapping from s → t
    if (mapST.has(c1)) {
      if (mapST.get(c1) !== c2) return false;
    } else {
      mapST.set(c1, c2);
    }

    // Check mapping from t → s
    if (mapTS.has(c2)) {
      if (mapTS.get(c2) !== c1) return false;
    } else {
      mapTS.set(c2, c1);
    }
  }

  return true;
}

console.log(areIsomorphic("egg", "add"));     
console.log(areIsomorphic("foo", "bar"));     
console.log(areIsomorphic("paper", "title")); 



/*
run:

true
false
true

*/

 



answered Dec 19, 2025 by avibootz
0 votes
function areIsomorphic(s, t) {
  const pattern = str => [...str].map(ch => str.indexOf(ch));
  
  return pattern(s).join() === pattern(t).join();
}

console.log(areIsomorphic("egg", "add"));     
console.log(areIsomorphic("foo", "bar"));     
console.log(areIsomorphic("paper", "title")); 



/*
run:

true
false
true

*/

 



answered Dec 19, 2025 by avibootz
...