Find the longest common prefix (LCP) in a given set of strings.

For example,

Input:
 
keys = [codable, code, coder, coding]
 
Output:
 
The longest common prefix is cod

Practice this problem

In the below post, we have discussed a solution using the divide-and-conquer technique to solve the LCP problem. In this post, a Trie-based solution is discussed.

Longest Common Prefix (LCP) Problem

 
Since all descendants of a Trie node have a common prefix of the string associated with that node, Trie (Prefix Tree) is the best data structure for this problem. We start by inserting all keys into the Trie. Then traverse the Trie until we find a leaf node or node with more than one child. All characters in the Trie path form the longest common prefix. For example,

LCP

Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

The longest common prefix is cod

Java


Download  Run Code

Output:

The longest common prefix is cod

Python


Download  Run Code

Output:

The longest common prefix is cod

The time complexity of the above solution is O(N.M), where N is the total number of given words and M is the maximum word length. The auxiliary space required by the program is O(N × M).