Skip to content

Instantly share code, notes, and snippets.

@dan-coulter
Last active September 1, 2021 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dan-coulter/e2f39c635a1c25e03bee86f96300d3cc to your computer and use it in GitHub Desktop.
Save dan-coulter/e2f39c635a1c25e03bee86f96300d3cc to your computer and use it in GitHub Desktop.
Find longest common string prefix
// Find the longest common prefix
const longestPrefix = (arr) => {
// Handle a couple of invalid inputs
if (!arr || !Array.isArray(arr) || arr.length === 0) {
return '';
// Bypass the loop if there's only one element in the array
} else if (arr.length === 1) {
return arr[0];
}
let prefix = '';
const firstWord = arr[0];
// We only need to loop through the first word
for (let i = 0; i < firstWord.length; i++) {
// Every word has to have the same character at the same location for the loop to continue
if (arr.every(x => x[i] === firstWord[i])) {
// If they match, append the character to the prefix
prefix += firstWord[i];
} else {
// If they don't match, boot us out of the loop.
break;
}
}
return prefix;
};
console.log(longestPrefix(["cranberry","crawfish","crap"]))
console.log(longestPrefix(["parrot", "poodle", "fish"]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment