Skip to content

Instantly share code, notes, and snippets.

@lndgalante
Created May 5, 2025 13:11
Show Gist options
  • Select an option

  • Save lndgalante/4f5f0178fa1b6f42acf0bf9b685edbf0 to your computer and use it in GitHub Desktop.

Select an option

Save lndgalante/4f5f0178fa1b6f42acf0bf9b685edbf0 to your computer and use it in GitHub Desktop.
Longest Common Prefix
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