Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python Program To Find Longest Common Prefix Using Word By Word Matching

  • Last Updated : 03 Jan, 2022

Given a set of strings, find the longest common prefix. 

Input  : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}
Output : "gee"

Input  : {"apple", "ape", "april"}
Output : "ap"

We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.
Now let us introduce another word “geek”. So now what is the longest common prefix in these three words ? It is “geek”
We can see that the longest common prefix holds the associative property, i.e-

LCP(string1, string2, string3) 
         = LCP (LCP (string1, string2), string3)

Like here

LCP (“geeksforgeeks”, “geeks”, “geek”)
     =  LCP (LCP (“geeksforgeeks”, “geeks”), “geek”)
     =  LCP (“geeks”, “geek”) = “geek”

So we can make use of the above associative property to find the LCP of the given strings. We one by one calculate the LCP of each of the given string with the LCP so far. The final result will be our longest common prefix of all the strings.
Note that it is possible that the given strings have no common prefix. This happens when the first character of all the strings are not same.
We show the algorithm with the input strings- “geeksforgeeks”, “geeks”, “geek”, “geezer” by the below figure.


Below is the implementation of above approach: 


# Python3 Program to find the longest 
# common prefix
# A Utility Function to find the common 
# prefix between strings- str1 and str2
def commonPrefixUtil(str1, str2):
    result = "";
    n1 = len(str1)
    n2 = len(str2)
    # Compare str1 and str2
    i = 0
    j = 0
    while i <= n1 - 1 and j <= n2 - 1:    
        if (str1[i] != str2[j]):
        result += str1[i]
        i += 1
        j += 1
    return (result)
# A Function that returns the longest 
# common prefix from the array of strings
def commonPrefix (arr, n):
    prefix = arr[0]
    for i in range (1, n):
        prefix = commonPrefixUtil(prefix, 
    return (prefix)
# Driver Code
if __name__ =="__main__":
    arr = ["geeksforgeeks", "geeks",
           "geek", "geezer"]
    n = len(arr)
    ans = commonPrefix(arr, n)
    if (len(ans)):
        print ("The longest common prefix is -",
        print("There is no common prefix")
# This code is contributed by ita_c

Output :

The longest common prefix is - gee

Time Complexity : Since we are iterating through all the strings and for each string we are iterating though each characters, so we can say that the time complexity is O(N M) where, 

N = Number of strings
M = Length of the largest string string 

Auxiliary Space : To store the longest prefix string we are allocating space which is O(M).
Please refer complete article on Longest Common Prefix using Word by Word Matching for more details!

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!