Last active
September 1, 2021 06:00
-
-
Save dan-coulter/e2f39c635a1c25e03bee86f96300d3cc to your computer and use it in GitHub Desktop.
Find longest common string prefix
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
// 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