Skip to content

Instantly share code, notes, and snippets.

@CarlaTeo
Created May 30, 2021 04:00
Show Gist options
  • Save CarlaTeo/47334c07bb4bd7c9e7b4669f9437cb32 to your computer and use it in GitHub Desktop.
Save CarlaTeo/47334c07bb4bd7c9e7b4669f9437cb32 to your computer and use it in GitHub Desktop.
[JS] Matching pairs
function getCharactersDistribution(string) {
const result = {};
string.split("").forEach((char, idx) => {
if(result[char]) result[char].add(String(idx));
else result[char] = new Set([String(idx)]);
});
return result;
}
function matchingPairs(s, t) {
const primaryTargets = {};
let secondaryTargetsCount = 0;
const tMap = getCharactersDistribution(t);
let matchingPairs = 0;
s.split('').forEach((char, idx) => {
if(tMap[char]) {
if(tMap[char].has(String(idx))) {
matchingPairs++;
}
else {
primaryTargets[idx] = tMap[char];
}
}
else {
secondaryTargetsCount++;
}
});
if(Object.keys(primaryTargets).length > 0) {
for(let idx of Object.keys(primaryTargets)) {
const desiredIndexes = primaryTargets[idx];
for(let idx2 of desiredIndexes) {
if(primaryTargets[idx2].has(idx)) return matchingPairs + 2;
}
}
return matchingPairs + 1;
}
if(secondaryTargetsCount > 1) {
return matchingPairs;
}
if(secondaryTargetsCount === 1) {
return Math.max(matchingPairs - 1, 0);
}
return Math.max(matchingPairs - 2, 0);
}
// ---------------------------------------------------------- Test ---------------------------------------- //
console.log(matchingPairs('', '')); // 0 [could be change to throw an error since it wasnt possible to swap]
console.log(matchingPairs('a', 'a')); // 0 [could be change to throw an error since it wasnt possible to swap]
console.log(matchingPairs('a', 'b')); // 0 [could be change to throw an error since it wasnt possible to swap]
console.log(matchingPairs('ab', 'ab')); // 0
console.log(matchingPairs('ab', 'ba')); // 2
console.log(matchingPairs('abcd', 'dcba')); // 2
console.log(matchingPairs('abcde', 'adcbe')); // 5
console.log(matchingPairs('abc', 'abe')); // 1
console.log(matchingPairs('abcd', 'abef')); // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment