Monday, October 6, 2025
HomeData Modelling & AIC++ Program To Find Longest Common Prefix Using Sorting

C++ Program To Find Longest Common Prefix Using Sorting

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

Input: {"neveropen", "neveropen", "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.  

  1. Word by Word Matching
  2. Character by Character Matching
  3. Divide and Conquer
  4. Binary Search.
  5. 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++




// C++ program to find longest common prefix
// of given array of words.
#include<iostream>
#include<algorithm>
 
using namespace std;
 
// Function to find the longest common prefix
string longestCommonPrefix(string ar[], int n)
{
 
    // If size is 0, return empty string
    if (n == 0)
        return "";
 
    if (n == 1)
        return ar[0];
 
    // Sort the given array
    sort(ar, ar + n);
 
    // Find the minimum length from
    // first and last string
    int en = min(ar[0].size(),
                 ar[n - 1].size());
 
    // Now the common prefix in first and
    // last string is the longest common prefix
    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;
}
 
// Driver Code
int main()
{
    string ar[] = {"neveropen", "neveropen",
                           "geek", "geezer"};
    int n = sizeof(ar) / sizeof(ar[0]);
    cout << "The longest common prefix is: "
         << longestCommonPrefix(ar, n);
    return 0;
}
 
// This code is contributed by jrolofmeister


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!

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!

RELATED ARTICLES

Most Popular

Dominic
32337 POSTS0 COMMENTS
Milvus
86 POSTS0 COMMENTS
Nango Kala
6707 POSTS0 COMMENTS
Nicole Veronica
11871 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11936 POSTS0 COMMENTS
Shaida Kate Naidoo
6823 POSTS0 COMMENTS
Ted Musemwa
7089 POSTS0 COMMENTS
Thapelo Manthata
6779 POSTS0 COMMENTS
Umr Jansen
6779 POSTS0 COMMENTS