#BlackLivesMatter Support An Initiative

The Longest Common Prefix Amongst An Array of Strings – Implementation in Javascript and PHP

Today, we’ll take a look at another easy problem on leetcode, finding the longest common prefix string amongst an array of strings.


Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Example 2:

Note: All given inputs are in lowercase letters a-z.


My approach to the above is to keep track of a nextCharacter  variable. nextCharacter will be initiated to the first character of the first string in the array. I’ll also define an empty variable, longestPrefix to keep track of the longest prefix :).

Within a while loop, we can first check for the length of the array or the first character of the first string. If array or character is empty we return an empty string. There’s nothing much we can do here. Else, we initiate nextCharacter to the char of the first string.

We’ll use the first string in the array as our reference for checking the longest common prefix. This means, we will loop through the characters of the strings in the array, updating the nextCharacter outside of the loop, and checking if the current character of each string at the specified position is the same as the nextCharacter. If at any point, there’s a difference, regardless of which string we’re comparing, we return an empty string. Else, we keep going, appending nextCharacter to the longestPrefix variable.

Within a for loop, we begin checking each string in the array for a common prefix. We do this by checking if the character of the current string at an index is different from the nextCharacter (derived from our first string in the array), if different, we return an empty string, else, we increase a counter for moving to the next character of the first (reference) string.  We then append, nextCharacter to longestPrefix.

Implementation in Javascript

Implementation in PHP

Do you have a different/faster approach? Please share below. Thanks for reading.


Leave a Comment

Your email address will not be published. Required fields are marked *