Last active
September 24, 2019 15:01
-
-
Save rromanovsky/7bfbb0679078c66b56ab255080a9860f to your computer and use it in GitHub Desktop.
Google's interview question (https://www.youtube.com/watch?v=10WnvBk9sZc)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const input = [ | |
['', ''], | |
['ABAZDC', 'BACBAD'], | |
['BACBAD', 'ABAZDC'], | |
['AGGTAB', 'GXTXAYB'], | |
['ABBA', 'BABAABAB'], | |
['GT', 'XCDFGRGDTRIFG'], | |
]; | |
const output = [ | |
'', | |
'ABAD', | |
'ABAD', | |
'GTAB', | |
'ABBA', | |
'GT', | |
]; | |
const algo = ([str1, str2]) => { | |
function findSequence(string1, string2) { | |
let sequence = ''; | |
let prevCharAt = 0; | |
string1.split('').forEach((char) => { | |
const charAt = string2.substr(prevCharAt).indexOf(char); | |
if (charAt > -1) { | |
prevCharAt = prevCharAt + charAt + 1; | |
sequence += char; | |
} | |
}); | |
return sequence; | |
} | |
const sequense = findSequence(str1, str2); | |
const sequense2 = findSequence(str2, str1); | |
return sequense.length > sequense2.length ? sequense : sequense2; | |
}; | |
const result = input.map(algo); | |
const valid = JSON.stringify(output) === JSON.stringify(result); | |
console.log('valid: ', valid); // To be true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment