Pair of strings having longest common prefix of maximum length in given array
Last Updated :
06 Apr, 2023
Given an array of strings arr[], the task is to find the pair of strings from the given array whose length of the longest common prefix between them is maximum. If multiple solutions exist, then print any one of them.
Examples:
Input: arr[] = {“geeksforgeeks”, “geeks”, “geeksforcse”, }
Output: (geeksforgeeks, geeksforcse)
Explanation:
All possible pairs and their longest common prefix are:
(“geeksforgeeks”, “geeks”) has the longest common prefix = “geeks”
(“geeksforgeeks”, “geeksforcse”) has the longest common prefix = “geeksfor”
(“geeks”, “geeksforcse”) has the longest common prefix = “geeks”
Therefore, a pair having maximum length of the longest common prefix is (“geeksforgeeks”, “geeksforcse”)
Input: arr[] = {“abbcbgfh”, “bcdee”, “bcde”, “abbcbde”}
Output: (abbcbgfh, abbcbde)
Naive Approach: The simplest approach to solve this problem is to generate all possible pairs of the given array and calculate the length of the longest common prefix of each pair. Finally, print the pair having a maximum length of the longest common prefix.
C++
#include <bits/stdc++.h>
using namespace std;
int longestCommonPrefix(string str1, string str2) {
int i = 0, j = 0, count = 0;
while (i < str1.length() && j < str2.length()) {
if (str1[i] != str2[j]) {
break ;
}
count++;
i++;
j++;
}
return count;
}
void findMaxLenPair(vector<string>& arr, int N)
{
int maxLen = -1;
string first, second;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
int len = longestCommonPrefix(arr[i], arr[j]);
if (len > maxLen) {
maxLen = len;
first = arr[i];
second = arr[j];
}
}
}
cout << "(" << first << " " << second << ")" ;
}
int main()
{
vector<string> arr
= { "geeksforgeeks" , "geeks" , "geeksforcse" };
int N = arr.size();
findMaxLenPair(arr, N);
return 0;
}
|
Java
import java.util.*;
public class Main {
public static int longestCommonPrefix(String str1, String str2)
{
int i = 0 , j = 0 , count = 0 ;
while (i < str1.length() && j < str2.length())
{
if (str1.charAt(i) != str2.charAt(j)) {
break ;
}
count++;
i++;
j++;
}
return count;
}
public static void findMaxLenPair(List<String> arr, int N)
{
int maxLen = - 1 ;
String first = "" , second = "" ;
for ( int i = 0 ; i < N; i++) {
for ( int j = i + 1 ; j < N; j++) {
int len = longestCommonPrefix(arr.get(i), arr.get(j));
if (len > maxLen) {
maxLen = len;
first = arr.get(i);
second = arr.get(j);
}
}
}
System.out.println( "(" + first + " " + second + ")" );
}
public static void main(String[] args) {
List<String> arr = new ArrayList<String>(
Arrays.asList( "geeksforgeeks" , "geeks" , "geeksforcse" )
);
int N = arr.size();
findMaxLenPair(arr, N);
}
}
|
Python3
def longestCommonPrefix(str1, str2):
i, j, count = 0 , 0 , 0
while (i < len (str1) and j < len (str2)):
if (str1[i] ! = str2[j]):
break
count + = 1
i + = 1
j + = 1
return count
def findMaxLenPair(arr, N):
maxLen = - 1
first, second = " ", " "
for i in range (N):
for j in range (i + 1 , N):
len = longestCommonPrefix(arr[i], arr[j])
if len > maxLen:
maxLen = len
first = arr[i]
second = arr[j]
print ( "(" , first, " " , second, ")" )
if __name__ = = '__main__' :
arr = [ "geeksforgeeks" , "geeks" , "geeksforcse" ]
N = len (arr)
findMaxLenPair(arr, N)
|
Javascript
function longestCommonPrefix(str1, str2) {
let i = 0, j = 0, count = 0;
while (i < str1.length && j < str2.length) {
if (str1[i] !== str2[j]) {
break ;
}
count++;
i++;
j++;
}
return count;
}
function findMaxLenPair(arr, N) {
let maxLen = -1;
let first = "" , second = "" ;
for (let i = 0; i < N; i++) {
for (let j = i + 1; j < N; j++) {
let len = longestCommonPrefix(arr[i], arr[j]);
if (len > maxLen) {
maxLen = len;
first = arr[i];
second = arr[j];
}
}
}
console.log( "(" , first, " " , second, ")" );
}
function main() {
let arr = [ "geeksforgeeks" , "geeks" , "geeksforcse" ];
let N = arr.length;
findMaxLenPair(arr, N);
}
main();
|
C#
using System;
using System.Collections.Generic;
public class GFG {
static int longestCommonPrefix( string str1, string str2) {
int i = 0, j = 0, count = 0;
while (i < str1.Length && j < str2.Length) {
if (str1[i] != str2[j]) {
break ;
}
count++;
i++;
j++;
}
return count;
}
static void findMaxLenPair(List< string > arr, int N) {
int maxLen = -1;
string first = "" , second = "" ;
for ( int i = 0; i < N; i++) {
for ( int j = i + 1; j < N; j++) {
int len = longestCommonPrefix(arr[i], arr[j]);
if (len > maxLen) {
maxLen = len;
first = arr[i];
second = arr[j];
}
}
}
Console.WriteLine( "(" + first + " " + second + ")" );
}
static void Main( string [] args) {
List< string > arr = new List< string > { "geeksforgeeks" , "geeks" , "geeksforcse" };
int N = arr.Count;
findMaxLenPair(arr, N);
}
}
|
Output
(geeksforgeeks geeksforcse)
Time Complexity: O(N2 * M), Where M denotes the length of the longest string
Auxiliary Space: O(1)
Efficient Approach: The problem can be solved using Trie. The idea is to traverse the given array and for each array element, find the maximum length of the longest prefix present in Trie, and insert the current element into the Trie. Finally, print the pair having a maximum length of the longest common prefix. Follow the steps below to solve the problem:
- Create a Trie having root node, say root to store each element of the given array.
- Traverse the given array and for each array element, find the maximum length of the longest prefix present in Trie and insert the current element into Trie.
- Finally, print the pair having a maximum length of the longest common prefix.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct TrieNode {
TrieNode* child[256];
TrieNode() { child[0] = child[1] = NULL; }
};
void insertTrie(TrieNode* root, string str)
{
int M = str.length();
for ( int i = 0; i < M; i++) {
if (!root->child[str[i]]) {
root->child[str[i]] = new TrieNode();
}
root = root->child[str[i]];
}
}
int findStrLen(TrieNode* root, string str)
{
int M = str.length();
int len = 0;
for ( int i = 0; i < M; i++) {
if (root->child[str[i]]) {
len++;
root = root->child[str[i]];
}
else {
return len;
}
}
return len;
}
void findMaxLenPair(vector<string>& arr, int N)
{
int idx = -1;
int len = 0;
TrieNode* root = new TrieNode();
insertTrie(root, arr[0]);
for ( int i = 1; i < N; i++) {
int temp = findStrLen(root, arr[i]);
if (temp > len) {
len = temp;
idx = i;
}
insertTrie(root, arr[i]);
}
for ( int i = 0; i < N; i++) {
int M = arr[i].length();
if (i != idx && M >= len) {
bool found = true ;
for ( int j = 0; j < len; j++) {
if (arr[i][j] != arr[idx][j]) {
found = false ;
break ;
}
}
if (found) {
cout << "(" << arr[i] << ", " << arr[idx]
<< ")" ;
return ;
}
}
}
}
int main()
{
vector<string> arr
= { "geeksforgeeks" , "geeks" , "geeksforcse" };
int N = arr.size();
findMaxLenPair(arr, N);
}
|
Java
import java.io.*;
import java.util.*;
class TrieNode {
TrieNode[] child = new TrieNode[ 256 ];
TrieNode() {}
}
class GFG {
private static void insertTrie(TrieNode root,
String str)
{
int M = str.length();
for ( int i = 0 ; i < M; i++) {
if (root.child[str.charAt(i)] == null ) {
root.child[str.charAt(i)] = new TrieNode();
}
root = root.child[str.charAt(i)];
}
}
private static int findStrLen(TrieNode root, String str)
{
int M = str.length();
int len = 0 ;
for ( int i = 0 ; i < M; i++) {
if (root.child[str.charAt(i)] != null ) {
len++;
root = root.child[str.charAt(i)];
}
else {
return len;
}
}
return len;
}
private static void findMaxLenPair(List<String> arr,
int N)
{
int idx = - 1 ;
int len = 0 ;
TrieNode root = new TrieNode();
insertTrie(root, arr.get( 0 ));
for ( int i = 1 ; i < N; i++) {
int temp = findStrLen(root, arr.get(i));
if (temp > len) {
len = temp;
idx = i;
}
insertTrie(root, arr.get(i));
}
for ( int i = 0 ; i < N; i++) {
int M = arr.get(i).length();
if (i != idx && M >= len) {
boolean found = true ;
for ( int j = 0 ; j < len; j++) {
if (arr.get(i).charAt(j)
!= arr.get(idx).charAt(j)) {
found = false ;
break ;
}
}
if (found) {
System.out.println( "(" + arr.get(i)
+ ", " + arr.get(idx)
+ ")" );
return ;
}
}
}
}
public static void main(String[] args)
{
List<String> arr = Arrays.asList( new String[] {
"geeksforgeeks" , "geeks" , "geeksforcse" });
int N = arr.size();
findMaxLenPair(arr, N);
}
}
|
Python3
class TrieNode:
def __init__( self ):
self .child = dict ()
def insertTrie(root, string):
M = len (string)
length = 0
for i in range (M):
if string[i] not in root.child:
root.child[string[i]] = TrieNode()
root = root.child[string[i]]
def findStrLen(root, string):
M = len (string)
length = 0
for i in range (M):
if string[i] not in root.child:
length + = 1
root = root.child[string[i]]
else :
return length
return length
def findMaxLenPair(arr, N):
idx = - 1
length = 0
root = TrieNode()
insertTrie(root, arr[ 0 ])
for i in range ( 1 , N):
temp = findStrLen(root, arr[i])
if temp > length:
length = temp
idx = i
insertTrie(root, arr[i])
for i in range (N):
M = len (arr[i])
if (i ! = idx and M > = length):
found = True
for j in range (length):
if arr[i][j] ! = arr[idx][j]:
found = False
break
if (found):
print ( "(" + arr[i] + ", " + arr[idx] + ")" )
return
arr = [ "geeksforgeeks" , "geeks" , "geeksforcse" ]
N = len (arr)
findMaxLenPair(arr, N)
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public class TrieNode
{
public TrieNode[] child = new TrieNode[256];
public TrieNode() {}
};
public static void insertTrie(TrieNode root,
String str)
{
int M = str.Length;
for ( int i = 0; i < M; i++) {
if (root.child[str[i]] == null ) {
root.child[str[i]] = new TrieNode();
}
root = root.child[str[i]];
}
}
public static int findStrLen(TrieNode root, String str)
{
int M = str.Length;
int len = 0;
for ( int i = 0; i < M; i++) {
if (root.child[str[i]] != null ) {
len++;
root = root.child[str[i]];
}
else {
return len;
}
}
return len;
}
public static void findMaxLenPair(List< string > arr,
int N)
{
int idx = -1;
int len = 0;
TrieNode root = new TrieNode();
insertTrie(root, arr[0]);
for ( int i = 1; i < N; i++) {
int temp = findStrLen(root, arr[i]);
if (temp > len) {
len = temp;
idx = i;
}
insertTrie(root, arr[i]);
}
for ( int i = 0; i < N; i++) {
int M = arr[i].Length;
if (i != idx && M >= len) {
bool found = true ;
for ( int j = 0; j < len; j++) {
if (arr[i][j] != arr[idx][j]) {
found = false ;
break ;
}
}
if (found) {
Console.WriteLine( "(" + arr[i]+ ", " + arr[idx]+ ")" );
return ;
}
}
}
}
public static void Main()
{
List< string > arr = new List< string >() { "geeksforgeeks" , "geeks" , "geeksforcse" };
int N = arr.Count;
findMaxLenPair(arr, N);
}
}
|
Javascript
<script>
class TrieNode
{
constructor()
{
this .child = Array(256);
}
};
function insertTrie(root, str)
{
var M = str.length;
for ( var i = 0; i < M; i++)
{
if (root.child[str[i]] == null )
{
root.child[str[i]] = new TrieNode();
}
root = root.child[str[i]];
}
}
function findStrLen(root, str)
{
var M = str.length;
var len = 0;
for ( var i = 0; i < M; i++)
{
if (root.child[str[i]] != null )
{
len++;
root = root.child[str[i]];
}
else
{
return len;
}
}
return len;
}
function findMaxLenPair(arr, N)
{
var idx = -1;
var len = 0;
var root = new TrieNode();
insertTrie(root, arr[0]);
for ( var i = 1; i < N; i++)
{
var temp = findStrLen(root, arr[i]);
if (temp > len)
{
len = temp;
idx = i;
}
insertTrie(root, arr[i]);
}
for ( var i = 0; i < N; i++)
{
var M = arr[i].length;
if (i != idx && M >= len)
{
var found = true ;
for ( var j = 0; j < len; j++)
{
if (arr[i][j] != arr[idx][j])
{
found = false ;
break ;
}
}
if (found)
{
document.write( "(" + arr[i] +
", " + arr[idx] + ")" );
return ;
}
}
}
}
var arr = [ "geeksforgeeks" , "geeks" ,
"geeksforcse" ];
var N = arr.length;
findMaxLenPair(arr, N);
</script>
|
Output:
(geeksforgeeks, geeksforcse)
Time Complexity: O(N * M), where M denotes the length of the longest string
Auxiliary Space: 0(N * 256)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...