Skip to content

Instantly share code, notes, and snippets.

@redrambles
Last active August 31, 2021 00:20
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 redrambles/78c7819943502730406bd523e4e7d487 to your computer and use it in GitHub Desktop.
Save redrambles/78c7819943502730406bd523e4e7d487 to your computer and use it in GitHub Desktop.
const wordArray = ['cranberry', 'crawfish', 'crap'];
const longestPrefix = (wordArray) => {
// Find the smallest word - our prefix cannot be any longer
const smallestWord = wordArray.reduce((acc, word) => {
return word.length <= acc.length ? word : acc;
});
let indexNoMatch = [];
for (let word of wordArray) {
for (let i = 0; i < smallestWord.length; i++) {
if (word[i] !== smallestWord[i]) {
indexNoMatch.push(i);
}
}
}
// Grab smallest number in indexNoMatch array - that's where the common letters for all words end
const smallestNumber = indexNoMatch.reduce((acc, num) => {
return num <= acc ? num : acc;
});
const commonPrefix = smallestWord
.split('')
.splice(0, smallestNumber)
.join('');
console.log(commonPrefix);
};
longestPrefix(wordArray); // "cra"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment