JSFiddle - React, Tailwind, and code Playground
by Mixail
JavaScript
/*
https://www.youtube.com/watch?v=10WnvBk9sZc
started at 22:53
first result at 23:12
19 mins
optimized solution at 23:18
+6 mins
total 25 mins
*/
/*
ABAZDC, BACBAD = ABAD
*/
function commonInArrays(a1, a2) {
let r = [];
a1.forEach(letter => {
const nextLetterIndex = a2.findIndex(l => l === letter);
if (nextLetterIndex === -1) {
return;
}
r.push(letter);
a2 = a2.slice(nextLetterIndex + 1);
});
return r.join("");
}
function common(s1, s2) {
let a1 = s1.split("");
let a2 = s2.split("");
let r = "";
while (true) {
const str = commonInArrays(a1, a2)
if (str.length > r.length) {
r = str;
}
a1 = a1.slice(1);
if (a1.length === 0 || r.length >= a1.length) {
break;
}
}
return r;
}
console.log(common('ABAZDC', 'BACBAD'));
console.log(common('AGGTAB', 'GXTXAYB'));
console.log(common('aaaa', 'aa'));
console.log('--------');