Skip to content

Instantly share code, notes, and snippets.

@olegon
Created February 15, 2023 00:29
Show Gist options
  • Save olegon/c48ce055e52bcb83cd8ed0ed9194328c to your computer and use it in GitHub Desktop.
Save olegon/c48ce055e52bcb83cd8ed0ed9194328c to your computer and use it in GitHub Desktop.
function longestPrefix(words) {
if (words.length == 0) return `""`;
const longestPossiblePrefixSize = Math.min(...words.map(word => word.length))
for (let prefixSize = longestPossiblePrefixSize; prefixSize > 0; prefixSize--) {
const [ firstWord, ...otherWords ] = words
if (otherWords.every(word => word.substr(0, prefixSize) == firstWord.substr(0, prefixSize))) {
return `"${firstWord.substr(0, prefixSize)}"`;
}
}
return `""`;
}
console.log(
longestPrefix(['flower', 'flow', 'flight'])
)
console.log(
longestPrefix(['dog', 'racecar', 'car'])
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment