# Determine whether there exists a one-to-one character mapping from one string to another

Determine whether there exists a one-to-one character mapping from one string s1 to another s2.

For example, given s1 = abc and s2 = bcd, return true since we can map a to b, b to c, and c to d.

Given s1 = foo and s2 = bar, return false since the o cannot map to two characters.

The task is ambiguous. Here are my interpretations of the task and the corresponding solution:

Interpretation 1:

For every letter in one string there exists exactly one in the other. (order and position of the corresponding letter are irrelevant)

My solution

const s1 = "foo";
const s2 = "bar";

const isMappable = (s1, s2) => {
if (s1.length !== s2.length) { return false; }

const createOrderedMap = str => Object.values([...str]
.reduce((map, s) => {
map[s] = map[s] ? map[s] + 1 : 1;
return map;
}, {})).sort();
const o1 = createOrderedMap(s1);
const o2 = createOrderedMap(s2);
if (o1.length !== o2.length) { return false; }
for (let i = 0, len = o1.length; i < len; i++) {
if (o1[i] !== o2[i]) {
return false;
}
}
return true;
};

console.log(isMappable(s1, s2));


Interpretation 2:

For every letter in one string there exists exactly one in the other at the exact order and position of the corresponding letter.

My solution

const s1 = "aab";
const s2 = "cdc";
const isMappable = (s1, s2) => {
if (s1.length !== s2.length) { return false; }

const map1 = new Map();
const map2 = new Map();

return [...s1].every((s, i) => {
if (!map1.has(s) && !map2.has(s2[i])) {
map2.set(s2[i], s);
map1.set(s, s2[i]);
}
return map1.get(s) === s2[i]  && map2.get(s2[i]) === s;
});
};

console.log(isMapable(s1, s2));

• Is there a mapping between abbb and cdcd? – vnp Apr 20 '19 at 19:08
• @vpn You are right. Fixed. – thadeuszlay Apr 20 '19 at 22:21
• returns true for aab,xyx; seems incorrect to me? I read this problem as "can string A be transformed to string B by substitution cipher?" – Oh My Goodness Apr 21 '19 at 9:34
• a can be mapped to one x, the other a to the other x, and b can be mapped to y? @OhMyGoodness – thadeuszlay Apr 21 '19 at 9:35
• update only checks one direction isMapable("abc","ddd") should be false (is many-to-one instead of one-to-one). And mappable is spelled with 2 p's :) – Oh My Goodness Apr 21 '19 at 16:55