Longest Common Prefix using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.
Examples:
Input: {“w3wiki”, “Beginner”, “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.
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++ 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 size is 1 then just return that character
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[] = {"w3wiki", "Beginner",
"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
// Java program to find longest common prefix of
// given array of words.
import java.util.*;
public class GFG
{
public String longestCommonPrefix(String[] a)
{
int size = a.length;
/* if size is 0, return empty string */
if (size == 0)
return "";
if (size == 1)
return a[0];
/* sort the array of strings */
Arrays.sort(a);
/* find the minimum length from first and last string */
int end = Math.min(a[0].length(), a[size-1].length());
/* find the common prefix between the first and
last string */
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;
}
/* Driver Function to test other function */
public static void main(String[] args)
{
GFG gfg = new GFG();
String[] input = {"w3wiki", "Beginner", "geek", "geezer"};
System.out.println( "The longest Common Prefix is : " +
gfg.longestCommonPrefix(input));
}
}
# Python 3 program to find longest
# common prefix of given array of words.
def longestCommonPrefix( a):
size = len(a)
# if size is 0, return empty string
if (size == 0):
return ""
if (size == 1):
return a[0]
# sort the array of strings
a.sort()
# find the minimum length from
# first and last string
end = min(len(a[0]), len(a[size - 1]))
# find the common prefix between
# the first and last string
i = 0
while (i < end and
a[0][i] == a[size - 1][i]):
i += 1
pre = a[0][0: i]
return pre
# Driver Code
if __name__ == "__main__":
input = ["w3wiki", "Beginner",
"geek", "geezer"]
print("The longest Common Prefix is :" ,
longestCommonPrefix(input))
# This code is contributed by ita_c
// C# program to find longest common prefix of
// given array of words.
using System;
public class GFG {
static string longestCommonPrefix(String[] a)
{
int size = a.Length;
/* if size is 0, return empty string */
if (size == 0)
return "";
if (size == 1)
return a[0];
/* sort the array of strings */
Array.Sort(a);
/* find the minimum length from first
and last string */
int end = Math.Min(a[0].Length,
a[size-1].Length);
/* find the common prefix between the
first and last string */
int i = 0;
while (i < end && a[0][i] == a[size-1][i] )
i++;
string pre = a[0].Substring(0, i);
return pre;
}
/* Driver Function to test other function */
public static void Main()
{
string[] input = {"w3wiki", "Beginner",
"geek", "geezer"};
Console.WriteLine( "The longest Common"
+ " Prefix is : "
+ longestCommonPrefix(input));
}
}
// This code is contributed by Sam007.
// Javascript program to find longest common prefix of
// given array of words.
function longestCommonPrefix(a)
{
let size = a.length;
/* if size is 0, return empty string */
if (size == 0)
return "";
if (size == 1)
return a[0];
/* sort the array of strings */
a.sort();
/* find the minimum length from first and last string */
let end = Math.min(a[0].length, a[size-1].length);
/* find the common prefix between the first and
last string */
let i = 0;
while (i < end && a[0][i] == a[size-1][i] )
i++;
let pre = a[0].substring(0, i);
return pre;
}
/* Driver Function to test other function */
let input=["w3wiki", "Beginner", "geek", "geezer"];
console.log( "The longest Common Prefix is : " +
longestCommonPrefix(input));
// This code is contributed by rag2127
Output
The longest common prefix is: gee
Time Complexity: O(n*log n)+O(m) where m is the size of minimum word in array and n is the number of strings in the input array.
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.
#include <bits/stdc++.h>
using namespace std;
string longestCommonPrefix(string arr[], int n)
{
// take temp_prefix string and assign first element of
// arr : a.
string result = arr[0];
int len = result.length();
// Iterate for rest of element in string.
for (int i = 1; i < n; i++) {
// .find() return index of that substring from
// string.
while (arr[i].find(result) != 0) {
// update matched substring prefx
result = result.substr(0, len - 1);
len--;
// check for empty case. direct return if true..
if (result.empty()) {
return "-1";
}
}
}
return result;
}
/* Driver Function to test other function */
int main()
{
string input[]
= { "w3wiki", "Beginner", "geek", "geezer" };
int n = sizeof(input) / sizeof(input[0]);
cout << "The longest Common Prefix is : "
<< longestCommonPrefix(input, n);
return 0;
}
// Java program to find longest common prefix of
// given array of words.
import java.util.*;
public class GFG
{
public String longestCommonPrefix(String[] arr)
{
int n = arr.length;
// take temp_prefix string and assign first element of arr : a.
String result = arr[0];
// Iterate for rest of element in string.
for(int i = 1; i < n; i++){
// .indexOf() return index of that substring from string.
while(arr[i].indexOf(result) != 0){
// update matched substring prefx
result = result.substring(0, result.length()-1);
// check for empty case. direct return if true..
if(result.isEmpty()){
return "-1";
}
}
}
return result;
}
/* Driver Function to test other function */
public static void main(String[] args)
{
GFG gfg = new GFG();
String[] input = {"w3wiki", "Beginner", "geek", "geezer"};
System.out.println( "The longest Common Prefix is : " +
gfg.longestCommonPrefix(input));
}
}
// this code is contributed by shantanu_mourya
def longestCommonPrefix(arr):
# Assign the first element of arr to result
result = arr[0]
length = len(result)
# Iterate for the rest of the elements in the array
for i in range(1, len(arr)):
# Find the index of result in the current string
while arr[i].find(result) != 0:
# Update the matched substring prefix
result = result[:length - 1]
length -= 1
# Check for an empty case and return if true
if not result:
return "-1"
return result
# Driver code to test the function
if __name__ == "__main__":
input_list = ["w3wiki", "Beginner", "geek", "geezer"]
print("The longest Common Prefix is:", longestCommonPrefix(input_list))
using System;
class Program
{
static string LongestCommonPrefix(string[] arr)
{
// Assign the first element of arr to result
string result = arr[0];
int length = result.Length;
// Iterate for the rest of the elements in the array
for (int i = 1; i < arr.Length; i++)
{
// Find the index of result in the current string
while (arr[i].IndexOf(result) != 0)
{
// Update the matched substring prefix
result = result.Substring(0, length - 1);
length--;
// Check for an empty case and return if true
if (result.Length == 0)
{
return "-1";
}
}
}
return result;
}
static void Main()
{
string[] input = { "w3wiki", "Beginner", "geek", "geezer" };
Console.WriteLine("The longest Common Prefix is: " + LongestCommonPrefix(input));
}
}
function longestCommonPrefix(arr) {
// Assign the first element of arr to result
let result = arr[0];
let length = result.length;
// Iterate for the rest of the elements in the array
for (let i = 1; i < arr.length; i++) {
// Find the index of result in the current string
while (arr[i].indexOf(result) !== 0) {
// Update the matched substring prefix
result = result.substring(0, length - 1);
length--;
// Check for an empty case and return if true
if (result === '') {
return '-1';
}
}
}
return result;
}
// Driver code to test the function
const input = ["w3wiki", "Beginner", "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.
Auxiliary Space: O(n)
Contact Us