tech interview
by Salmin Skenderovic
JavaScript
// "ABAZDC", "BACDBAD" => "ABAD"
// "AGGTAB", "GXTXAYB" => "GTAB"
// "aaaa", "aa" => "aa"
function getLongestSub(s1, s2) {
const allSubs = [];
const hashMap = {}
for (let i = 0; i < s1.length; i++) {
if (!!s2[i]) hashMap[s2[i]+i] = i
allSubs.push(getSubSequance(s1.slice(i), s2))
}
console.log(hashMap)
return allSubs.sort((a, b) => {
return b.length - a.length
})[0].join("")
}
// Returns 1 subseq
function getSubSequance(s1, s2) {
const sub = [];
let start = 0;
for (let i = 0; i < s1.length; i++) {
const foundIndex = findIndex(s1[i], s2, start);
if (foundIndex !== false) {
sub.push(s2[foundIndex])
start = foundIndex+1;
}
}
return sub;
}
function findIndex(char, s2, start) {
for (let i = start; i < s2.length; i++) {
if (char == s2[i]) return i;
}
return false
}
function test(s1, s2, r) {
const result = getLongestSub(s1, s2);
//console.log(r == result, result)
}
test("ABAZDC", "BACDBAD", "ABAD")
test("AGGTAB", "GXTXAYB", "GTAB")
test("aaaa", "aa", "aa")