WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Coding Interview Essentials · Array and String Problems · question 39 of 120

Can you find the longest common prefix in an array of strings?

📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

You can find the longest common prefix in an array of strings by using a character by character matching method. The algorithm starts with the first character and continues to the next character only if all the strings have the same character at the current position.

The time complexity of this approach is approximately O(N*M), where N is the number of strings, and M is the length of the largest string string in the array.

Algorithm:

1. Initialize a string ‘prefix‘ as the first string in the array.

2. Iterate through the array, and for each string, check whether it has ‘prefix‘ as a prefix. If not, shorten ‘prefix‘ by excluding the last character and proceed to the next string.

3. Repeat step 2 until either ‘prefix‘ becomes empty or it is a prefix of all the strings in the array.

4. Return ‘prefix‘.

Here is a Python example of the above algorithm:

def longestCommonPrefix(strs):
    if not strs:
        return ""

    prefix = strs[0]
    for string in strs[1:]:
        while not string.startswith(prefix):
            prefix = prefix[:-1]

            if not prefix:
                return ""
    return prefix

For an array of strings ‘strs = ["flower","flow","flight"]‘, the longest common prefix is "fl".

Please note that as this algorithm checks character by character from the beginning of each string, as soon as the strings no longer have a common character the algorithm stops, making it very efficient even for large lists of strings.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Coding Interview Essentials interview — then scores it.
📞 Practice Coding Interview Essentials — free 15 min
📕 Buy this interview preparation book: 120 Coding Interview Essentials questions & answers — PDF + EPUB for $5

All 120 Coding Interview Essentials questions · All topics