Write an efficient algorithm to find the longest common prefix (LCP) between a given set of strings.

For example,

Input:  technique, technician, technology, technical
Output: The longest common prefix is techn
 
 
Input:  techie delight, tech, techie, technology, technical
Output: The longest common prefix is tech

Practice this problem

A simple solution is to consider each string and calculate its longest common prefix with the longest common prefix of strings processed so far. The time complexity of this solution is O(N.M), where N is the total number of words and M is the maximum length of a word.

This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The longest common prefix is tech

Java


Download  Run Code

Output:

The longest common prefix is tech

Python


Download  Run Code

Output:

The longest common prefix is tech

We can also use the Divide and Conquer technique for finding the longest common prefix (LCP). Like all divide-and-conquer algorithms, the idea is to divide the strings into two smaller sets and then recursively process those sets. This is similar to the merge sort routine, except we find the LCP of the two halves instead of merging both halves.

C++


Download  Run Code

Output:

The longest common prefix is tech

Java


Download  Run Code

Output:

The longest common prefix is tech

Python


Download  Run Code

Output:

The longest common prefix is tech

The time complexity of the above solution is O(N.M), where N is the total number of words and M is the maximum length of a word. The auxiliary space used is O(M.log(N)) for the call stack.

 
Also See:

Longest Common Prefix in a given set of strings (Using Trie)