Skip to content

Instantly share code, notes, and snippets.

@PradatiusD
Created September 3, 2021 20:11
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 PradatiusD/9a3f34f480b1c380db5714c2119885b7 to your computer and use it in GitHub Desktop.
Save PradatiusD/9a3f34f480b1c380db5714c2119885b7 to your computer and use it in GitHub Desktop.
/**
* Write a function to find the longest common prefix string in an array of strings.
* --------------------------------
* Function to find matching characters and stop at the
* point at which they are different or if the string ends
*
* Worked with https://twitter.com/Spraggsz_ to solve!
* @return {string}
*/
function longestPrefix (arrayOfStrings) {
let string = ''
let shortestStringLength = null
for (const array of arrayOfStrings) {
const isSmaller = shortestStringLength === null || shortestStringLength > array.length
if (isSmaller) {
shortestStringLength = array.length
}
}
for (let i = 0; i < shortestStringLength; i++) {
// compare all arrayOfStrings[i] to see if they are equal
const firstChar = arrayOfStrings[0][i]
for (let j = 1; j < arrayOfStrings.length; j++) {
if (firstChar !== arrayOfStrings[j][i]) {
return string
}
}
string += firstChar
}
return string
}
longestPrefix([
"parrot",
"poodle",
"fish"
])
// ''
longestPrefix([
"cranberries",
"crawfish",
"crap"
])
// 'cra'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment