Thursday, July 4, 2024
HomeData ModellingData Structure & AlgorithmC++ Program To Find Longest Common Prefix Using Word By Word Matching

C++ Program To Find Longest Common Prefix Using Word By Word Matching

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

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

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

We start with an example. Suppose there are two strings- “neveropen” and “neveropen”. What is the longest common prefix in both of them? It is “neveropen”.
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 (“neveropen”, “neveropen”, “geek”)
     =  LCP (LCP (“neveropen”, “neveropen”), “geek”)
     =  LCP (“neveropen”, “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- “neveropen”, “neveropen”, “geek”, “geezer” by the below figure.

longest_common_prefix

Below is the implementation of above approach:

C++




//  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 str2
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.push_back(str1[i]);
    }
  
    return (result);
}
  
// A Function that returns the longest 
// common prefix from the array of strings
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 code
int main()
{
    string arr[] = {"neveropen", "neveropen",
                    "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);
}


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!

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments