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 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[] = { "neveropen" , "neveropen" ,
"geek" , "geezer" };
int n = sizeof (ar) / sizeof (ar[0]);
cout << "The longest common prefix is: "
<< longestCommonPrefix(ar, n);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
public String longestCommonPrefix(String[] a)
{
int size = a.length;
if (size == 0 )
return "" ;
if (size == 1 )
return a[ 0 ];
Arrays.sort(a);
int end = Math.min(a[ 0 ].length(), a[size- 1 ].length());
int i = 0 ;
while (i < end && a[ 0 ].charAt(i) == a[size- 1 ].charAt(i) )
i++;
String pre = a[ 0 ].substring( 0 , i);
return pre;
}
public static void main(String[] args)
{
GFG gfg = new GFG();
String[] input = { "neveropen" , "neveropen" , "geek" , "geezer" };
System.out.println( "The longest Common Prefix is : " +
gfg.longestCommonPrefix(input));
}
}
|
Python 3
def longestCommonPrefix( a):
size = len (a)
if (size = = 0 ):
return ""
if (size = = 1 ):
return a[ 0 ]
a.sort()
end = min ( len (a[ 0 ]), len (a[size - 1 ]))
i = 0
while (i < end and
a[ 0 ][i] = = a[size - 1 ][i]):
i + = 1
pre = a[ 0 ][ 0 : i]
return pre
if __name__ = = "__main__" :
input = [ "neveropen" , "neveropen" ,
"geek" , "geezer" ]
print ( "The longest Common Prefix is :" ,
longestCommonPrefix( input ))
|
C#
using System;
public class GFG {
static string longestCommonPrefix(String[] a)
{
int size = a.Length;
if (size == 0)
return "" ;
if (size == 1)
return a[0];
Array.Sort(a);
int end = Math.Min(a[0].Length,
a[size-1].Length);
int i = 0;
while (i < end && a[0][i] == a[size-1][i] )
i++;
string pre = a[0].Substring(0, i);
return pre;
}
public static void Main()
{
string [] input = { "neveropen" , "neveropen" ,
"geek" , "geezer" };
Console.WriteLine( "The longest Common"
+ " Prefix is : "
+ longestCommonPrefix(input));
}
}
|
Javascript
<script>
function longestCommonPrefix(a)
{
let size = a.length;
if (size == 0)
return "" ;
if (size == 1)
return a[0];
a.sort();
let end = Math.min(a[0].length, a[size-1].length);
let i = 0;
while (i < end && a[0][i] == a[size-1][i] )
i++;
let pre = a[0].substring(0, i);
return pre;
}
let input=[ "neveropen" , "neveropen" , "geek" , "geezer" ];
document.write( "The longest Common Prefix is : " +
longestCommonPrefix(input));
</script>
|
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 the 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)
Approach (2) :
The Idea is to find unique prefix without sorting the string array. Extract substring by comparing current substring with the previous substring and update it’s result. For large string it work much faster.
C++
#include <bits/stdc++.h>
using namespace std;
string longestCommonPrefix(string arr[], int n)
{
string result = arr[0];
int len = result.length();
for ( int i = 1; i < n; i++) {
while (arr[i].find(result) != 0) {
result = result.substr(0, len - 1);
len--;
if (result.empty()) {
return "-1" ;
}
}
}
return result;
}
int main()
{
string input[]
= { "neveropen" , "neveropen" , "geek" , "geezer" };
int n = sizeof (input) / sizeof (input[0]);
cout << "The longest Common Prefix is : "
<< longestCommonPrefix(input, n);
return 0;
}
|
Java
import java.util.*;
public class GFG
{
public String longestCommonPrefix(String[] arr)
{
int n = arr.length;
String result = arr[ 0 ];
for ( int i = 1 ; i < n; i++){
while (arr[i].indexOf(result) != 0 ){
result = result.substring( 0 , result.length()- 1 );
if (result.isEmpty()){
return "-1" ;
}
}
}
return result;
}
public static void main(String[] args)
{
GFG gfg = new GFG();
String[] input = { "neveropen" , "neveropen" , "geek" , "geezer" };
System.out.println( "The longest Common Prefix is : " +
gfg.longestCommonPrefix(input));
}
}
|
Python3
def longestCommonPrefix(arr):
result = arr[ 0 ]
length = len (result)
for i in range ( 1 , len (arr)):
while arr[i].find(result) ! = 0 :
result = result[:length - 1 ]
length - = 1
if not result:
return "-1"
return result
if __name__ = = "__main__" :
input_list = [ "neveropen" , "neveropen" , "geek" , "geezer" ]
print ( "The longest Common Prefix is:" , longestCommonPrefix(input_list))
|
C#
using System;
class Program
{
static string LongestCommonPrefix( string [] arr)
{
string result = arr[0];
int length = result.Length;
for ( int i = 1; i < arr.Length; i++)
{
while (arr[i].IndexOf(result) != 0)
{
result = result.Substring(0, length - 1);
length--;
if (result.Length == 0)
{
return "-1" ;
}
}
}
return result;
}
static void Main()
{
string [] input = { "neveropen" , "neveropen" , "geek" , "geezer" };
Console.WriteLine( "The longest Common Prefix is: " + LongestCommonPrefix(input));
}
}
|
Javascript
function longestCommonPrefix(arr) {
let result = arr[0];
let length = result.length;
for (let i = 1; i < arr.length; i++) {
while (arr[i].indexOf(result) !== 0) {
result = result.substring(0, length - 1);
length--;
if (result === '' ) {
return '-1' ;
}
}
}
return result;
}
const input = [ "neveropen" , "neveropen" , "geek" , "geezer" ];
console.log( "The longest Common Prefix is:" , longestCommonPrefix(input));
|
Output
The longest Common Prefix is : gee
Time Complexity : O ( m * N). where m is the length of the prefix and n is the number of strings in the input array.
This article is contributed by Saloni Baweja. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen 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.
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!