Created
May 5, 2025 13:11
-
-
Save lndgalante/4f5f0178fa1b6f42acf0bf9b685edbf0 to your computer and use it in GitHub Desktop.
Longest Common Prefix
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
| function longestCommonPrefix(words: string[]): string { | |
| if (words.length === 0) { | |
| return ""; | |
| } | |
| const prefixes = []; | |
| const firstWord = words[0] as string; | |
| for (let j = 0; j < firstWord.length; j++) { | |
| const prefix = firstWord.slice(0, j); | |
| const allOthersWordsStartsWithPrefix = words.slice(1).every((word) => word.startsWith(prefix)); | |
| if (allOthersWordsStartsWithPrefix) { | |
| prefixes.push(prefix); | |
| } | |
| } | |
| const longestPrefix = prefixes.at(-1) as string; | |
| return longestPrefix; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment