C++ 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.
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++
// 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[] = {"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);
}
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!
Similar Reads
C++ Program To Find Longest Common Prefix Using Sorting Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "geek", "geezer"} Output: "gee" Input: {"apple", "ape", "april"} Output: "ap" The longest common prefix for an array of strings is the common prefix between 2 most dissimilar strings
2 min read
C++ Program for Longest Common Subsequence LCS Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. For example, "abc", "abg", "bdf", "aeg", '"acefg", .. etc are subsequences of "abcdefg". So
3 min read
C++ Program To Find Length Of The Longest Substring Without Repeating Characters Given a string str, find the length of the longest substring without repeating characters. For âABDEFGABEFâ, the longest substring are âBDEFGAâ and "DEFGAB", with length 6.For âBBBBâ the longest substring is âBâ, with length 1.For "GEEKSFORGEEKS", there are two longest substrings shown in the below
6 min read
Find the longest string that can be made up of other strings from the array Given an array of strings arr[], the task is to find the largest string in the array which is made up of the other strings from the array after concatenating one after another. If no such string exists then print -1.Examples: Input: arr[] = {"geeks", "for", "geeksfor", "geeksforgeeks"} Output: geeks
9 min read
Longest prefix in a string with highest frequency Given a string, find a prefix with the highest frequency. If two prefixes have the same frequency then consider the one with the maximum length. Examples: Input : str = "abc" Output : abc Each prefix has same frequency(one) and the prefix with maximum length is "abc". Input : str = "abcab" Output :
7 min read