Created
February 15, 2023 00:29
-
-
Save olegon/c48ce055e52bcb83cd8ed0ed9194328c to your computer and use it in GitHub Desktop.
This file contains 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
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