Longest Common Prefix using Word by Word Matching - GeeksforGeeks

06 Apr, 2021
Given a set of strings, find the longest common prefix. Examples:  
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:  
C++
Java
Python3
C#
Javascript
//  A C++ Program to find the longest common prefix#include<bits/stdc++.h>using namespace std; // A Utility Function to find the common prefix between// strings- str1 and str2string commonPrefixUtil(string str1, string str2){    string result;    int n1 = str1.length(), n2 = str2.length();     // Compare str1 and str2    for (int i=0, j=0; i<=n1-1&&j<=n2-1; i++,j++)    {        if (str1[i] != str2[j])            break;        result.push_back(str1[i]);    }     return (result);} // A Function that returns the longest common prefix// from the array of stringsstring commonPrefix (string arr[], int n){    string prefix =  arr[0];     for (int i=1; i<=n-1; i++)        prefix = commonPrefixUtil(prefix, arr[i]);     return (prefix);} // Driver program to test above functionint main(){    string arr[] = {"geeksforgeeks", "geeks",                    "geek", "geezer"};    int n = sizeof(arr) / sizeof(arr[0]);     string ans = commonPrefix(arr, n);     if (ans.length())        printf ("The longest common prefix is - %s",                 ans.c_str());    else        printf("There is no common prefix");     return (0);}
// Java Program to find the longest common prefix class GFG { // A Utility Function to find the common prefix between// strings- str1 and str2    static String commonPrefixUtil(String str1, String str2) {        String result = "";        int n1 = str1.length(), n2 = str2.length();         // Compare str1 and str2        for (int i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {            if (str1.charAt(i) != str2.charAt(j)) {                break;            }            result += str1.charAt(i);        }         return (result);    } // A Function that returns the longest common prefix// from the array of strings    static String commonPrefix(String arr[], int n) {        String prefix = arr[0];         for (int i = 1; i <= n - 1; i++) {            prefix = commonPrefixUtil(prefix, arr[i]);        }         return (prefix);    } // Driver program to test above function    public static void main(String[] args) {        String arr[] = {"geeksforgeeks", "geeks",            "geek", "geezer"};        int n = arr.length;         String ans = commonPrefix(arr, n);         if (ans.length() > 0) {            System.out.printf("The longest common prefix is - %s",                    ans);        } else {            System.out.printf("There is no common prefix");        }    }}// This code is contributed by 29AjayKumar
# A python3 Program to find the longest# common prefix # A Utility Function to find the common# prefix between strings- str1 and str2def 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]):            break                     result += str1[i]        i += 1        j += 1     return (result) # A Function that returns the longest# common prefix from the array of stringsdef commonPrefix (arr, n):     prefix = arr[0]     for i in range (1, n):        prefix = commonPrefixUtil(prefix, arr[i])     return (prefix) # Driver Codeif __name__ =="__main__":     arr = ["geeksforgeeks", "geeks",                    "geek", "geezer"]    n = len(arr)     ans = commonPrefix(arr, n)     if (len(ans)):        print ("The longest common prefix is -",                ans);    else:        print("There is no common prefix") # This code is contributed by ita_c
// C# Program to find the longest// common prefixusing System; class GFG{ // A Utility Function to find// the common prefix between// strings- str1 and str2static String commonPrefixUtil(String str1,                               String str2){    String result = "";    int n1 = str1.Length,        n2 = str2.Length;     // Compare str1 and str2    for (int i = 0, j = 0;             i <= n1 - 1 && j <= n2 - 1;             i++, j++)    {        if (str1[i] != str2[j])        {            break;        }        result += str1[i];    }     return (result);} // A Function that returns the longest// common prefix from the array of stringsstatic String commonPrefix(String []arr, int n){    String prefix = arr[0];     for (int i = 1; i <= n - 1; i++)    {        prefix = commonPrefixUtil(prefix,                     arr.GetValue(i).ToString());    }     return (prefix);} // Driver Codepublic static void Main(){    String []arr = {"geeksforgeeks", "geeks",                    "geek", "geezer"};    int n = arr.Length;     String ans = commonPrefix(arr, n);     if (ans.Length > 0)    {        Console.Write("The longest common " +                       "prefix is - " + ans);    }    else    {        Console.Write("There is no common prefix");    }}} // This code is contributed// by 29AjayKumar
<script>// Javascript Program to find the longest common prefix         // A Utility Function to find the common prefix between    // strings- str1 and str2    function commonPrefixUtil(str1,str2)    {        let  result = "";        let n1 = str1.length, n2 = str2.length;        // Compare str1 and str2        for (let i = 0, j = 0; i <= n1 - 1 && j <= n2 - 1; i++, j++) {            if (str1[i] != str2[j]) {                break;            }            result += str1[i];        }           return (result);    }         // A Function that returns the longest common prefix    // from the array of strings    function commonPrefix(arr,n)    {        let prefix = arr[0];                 for (let i = 1; i <= n - 1; i++) {            prefix = commonPrefixUtil(prefix, arr[i]);        }           return (prefix);    }         // Driver program to test above function    let arr=["geeksforgeeks", "geeks",            "geek", "geezer"];    let n = arr.length;    let ans = commonPrefix(arr, n);    if (ans.length > 0) {        document.write("The longest common prefix is - ",                ans);    } else {        document.write("There is no common prefix ");    }         // This code is contributed by rag2127      </script>
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).How to improve this ? Please see Longest Common Prefix | Set 2 (Character by Character Matching)This article is contributed by Rachit Belwariar. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
29AjayKumar
ukasp
rag2127
Longest Common Prefix
VMWare
Arrays
Strings
VMWare
Arrays
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
Python program to check if a string is palindrome or not