C++ Program To Find Longest Common Prefix Using Sorting
Last Updated :
23 Mar, 2023
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. For example, in the given array {“apple”, “ape”, “zebra”}, there is no common prefix because the 2 most dissimilar strings of the array “ape” and “zebra” do not share any starting characters.
We have discussed five different approaches in below posts.
- Word by Word Matching
- Character by Character Matching
- Divide and Conquer
- Binary Search.
- Using Trie)
In this post a new method based on sorting is discussed. The idea is to sort the array of strings and find the common prefix of the first and last string of the sorted array.
C++
#include<iostream>
#include<algorithm>
using namespace std;
string longestCommonPrefix(string ar[], int n)
{
if (n == 0)
return "" ;
if (n == 1)
return ar[0];
sort(ar, ar + n);
int en = min(ar[0].size(),
ar[n - 1].size());
string first = ar[0], last = ar[n - 1];
int i = 0;
while (i < en && first[i] == last[i])
i++;
string pre = first.substr(0, i);
return pre;
}
int main()
{
string ar[] = { "geeksforgeeks" , "geeks" ,
"geek" , "geezer" };
int n = sizeof (ar) / sizeof (ar[0]);
cout << "The longest common prefix is: "
<< longestCommonPrefix(ar, n);
return 0;
}
|
Output
The longest common prefix is: gee
Time Complexity: O(MAX * n * log n ) where n is the number of strings in the array and MAX is maximum number of characters in any string. Please note that comparison of two strings would take at most O(MAX) time and for sorting n strings, we would need O(MAX * n * log n ) time.
Auxiliary Space: O(1) as no extra space has been used.
Please refer complete article on Longest Common Prefix using Sorting for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...