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++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to calculate length of longest common prefix
int longestCommonPrefix(string str1, string str2) {
int i = 0, j = 0, count = 0;
while (i < str1.length() && j < str2.length()) {
// If characters do not match, break the loop
if (str1[i] != str2[j]) {
break;
}
// Keep incrementing the count for each matching character
count++;
i++;
j++;
}
return count;
}
// Function to print the pair having maximum
// length of the longest common prefix
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++) {
// Get the length of the longest common prefix of the current pair
int len = longestCommonPrefix(arr[i], arr[j]);
// If the length of the current longest common prefix is
// greater than the maximum length seen so far then
// update the maximum length and the pair
if (len > maxLen) {
maxLen = len;
first = arr[i];
second = arr[j];
}
}
}
// Print pairs having maximum length
// of the longest common prefix
cout << "(" << first << " " << second << ")";
}
// Driver Code
int main()
{
vector<string> arr
= { "geeksforgeeks", "geeks", "geeksforcse" };
int N = arr.size();
findMaxLenPair(arr, N);
return 0;
}
// This code is contributed by Vaibhav.
Java
import java.util.*;
public class Main {
// Function to calculate length of longest common prefix
public static int longestCommonPrefix(String str1, String str2)
{
int i = 0, j = 0, count = 0;
while (i < str1.length() && j < str2.length())
{
// If characters do not match, break the loop
if (str1.charAt(i) != str2.charAt(j)) {
break;
}
// Keep incrementing the count for each matching character
count++;
i++;
j++;
}
return count;
}
// Function to print the pair having maximum
// length of the longest common prefix
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++) {
// Get the length of the longest common prefix of the current pair
int len = longestCommonPrefix(arr.get(i), arr.get(j));
// If the length of the current longest common prefix is
// greater than the maximum length seen so far then
// update the maximum length and the pair
if (len > maxLen) {
maxLen = len;
first = arr.get(i);
second = arr.get(j);
}
}
}
// Print pairs having maximum length
// of the longest common prefix
System.out.println("(" + first + " " + second + ")");
}
// Driver Code
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
# Python Program to implement the above approach
# Function to calculate length of longest common prefix
def longestCommonPrefix(str1, str2):
i, j, count = 0, 0, 0
while(i < len(str1) and j < len(str2)):
# If characters do not match, break the loop
if (str1[i] != str2[j]):
break
# Keep incrementing the count for each matching character
count += 1
i += 1
j += 1
return count
# Function to print the pair having maximum
# length of the longest common prefix
def findMaxLenPair(arr, N):
maxLen = -1
first, second = "", ""
for i in range(N):
for j in range(i+1, N):
# Get the length of the longest common prefix of the current pair
len = longestCommonPrefix(arr[i], arr[j])
# If the length of the current longest common prefix is
# greater than the maximum length seen so far then
# update the maximum length and the pair
if len > maxLen:
maxLen = len
first = arr[i]
second = arr[j]
# Print pairs having maximum length
# of the longest common prefix
print("(", first, " ", second, ")")
# Driver Code
if __name__ == '__main__':
arr = ["geeksforgeeks", "geeks", "geeksforcse"]
N = len(arr)
findMaxLenPair(arr, N)
JavaScript
// JS Program to implement the above approach
// Function to calculate length of longest common prefix
function longestCommonPrefix(str1, str2) {
let i = 0, j = 0, count = 0;
while (i < str1.length && j < str2.length) {
// If characters do not match, break the loop
if (str1[i] !== str2[j]) {
break;
}
// Keep incrementing the count for each matching character
count++;
i++;
j++;
}
return count;
}
// Function to print the pair having maximum
// length of the longest common prefix
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++) {
// Get the length of the longest common prefix of the current pair
let len = longestCommonPrefix(arr[i], arr[j]);
// If the length of the current longest common prefix is
// greater than the maximum length seen so far then
// update the maximum length and the pair
if (len > maxLen) {
maxLen = len;
first = arr[i];
second = arr[j];
}
}
}
// Print pairs having maximum length
// of the longest common prefix
console.log("(", first, " ", second, ")");
}
// Driver Code
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 {
// Function to calculate length of longest common prefix
static int longestCommonPrefix(string str1, string str2) {
int i = 0, j = 0, count = 0;
while (i < str1.Length && j < str2.Length) {
// If characters do not match, break the loop
if (str1[i] != str2[j]) {
break;
}
// Keep incrementing the count for each matching character
count++;
i++;
j++;
}
return count;
}
// Function to print the pair having maximum
// length of the longest common prefix
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++) {
// Get the length of the longest common prefix of the current pair
int len = longestCommonPrefix(arr[i], arr[j]);
// If the length of the current longest common prefix is
// greater than the maximum length seen so far then
// update the maximum length and the pair
if (len > maxLen) {
maxLen = len;
first = arr[i];
second = arr[j];
}
}
}
// Print pairs having maximum length
// of the longest common prefix
Console.WriteLine("(" + first + " " + second + ")");
}
// Driver Code
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++
// C++ program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Structure of Trie
struct TrieNode {
// Stores characters of
// each string
TrieNode* child[256];
TrieNode() { child[0] = child[1] = NULL; }
};
// Function to insert a string into Trie
void insertTrie(TrieNode* root, string str)
{
// Stores length of the string
int M = str.length();
// Traverse the string str
for (int i = 0; i < M; i++) {
// If str[i] is not present
// in current path of Trie
if (!root->child[str[i]]) {
// Create a new node
// of Trie
root->child[str[i]] = new TrieNode();
}
// Update root
root = root->child[str[i]];
}
}
// Function to find the maximum length of
// longest common prefix in Trie with str
int findStrLen(TrieNode* root, string str)
{
// Stores length of str
int M = str.length();
// Stores length of longest
// common prefix in Trie with str
int len = 0;
// Traverse the string str
for (int i = 0; i < M; i++) {
// If str[i] is present in
// the current path of Trie
if (root->child[str[i]]) {
// Update len
len++;
// Update root
root = root->child[str[i]];
}
else {
return len;
}
}
return len;
}
// Function to print the pair having maximum
// length of the longest common prefix
void findMaxLenPair(vector<string>& arr, int N)
{
// Stores index of the string having
// maximum length of longest common prefix
int idx = -1;
// Stores maximum length of longest
// common prefix.
int len = 0;
// Create root node of Trie
TrieNode* root = new TrieNode();
// Insert arr[0] into Trie
insertTrie(root, arr[0]);
// Traverse the array.
for (int i = 1; i < N; i++) {
// Stores maximum length of longest
// common prefix in Trie with arr[i]
int temp = findStrLen(root, arr[i]);
// If temp is greater than len
if (temp > len) {
// Update len
len = temp;
// Update idx
idx = i;
}
insertTrie(root, arr[i]);
}
// Traverse array arr[]
for (int i = 0; i < N; i++) {
// Stores length of arr[i]
int M = arr[i].length();
// Check if maximum length of
// longest common prefix > M
if (i != idx && M >= len) {
bool found = true;
// Traverse string arr[i]
// and arr[j]
for (int j = 0; j < len; j++) {
// If current character of both
// string does not match.
if (arr[i][j] != arr[idx][j]) {
found = false;
break;
}
}
// Print pairs having maximum length
// of the longest common prefix
if (found) {
cout << "(" << arr[i] << ", " << arr[idx]
<< ")";
return;
}
}
}
}
// Driver Code
int main()
{
vector<string> arr
= { "geeksforgeeks", "geeks", "geeksforcse" };
int N = arr.size();
findMaxLenPair(arr, N);
}
Java
// Java program for the above approach
import java.io.*;
import java.util.*;
// class of Trie
class TrieNode {
TrieNode[] child = new TrieNode[256];
TrieNode() {}
}
class GFG {
// Function to insert a string into Trie
private static void insertTrie(TrieNode root,
String str)
{
// Stores length of the string
int M = str.length();
// Traverse the string str
for (int i = 0; i < M; i++) {
// If str[i] is not present
// in current path of Trie
if (root.child[str.charAt(i)] == null) {
// Create a new node
// of Trie
root.child[str.charAt(i)] = new TrieNode();
}
// Update root
root = root.child[str.charAt(i)];
}
}
// Function to find the maximum length of
// longest common prefix in Trie with str
private static int findStrLen(TrieNode root, String str)
{
// Stores length of str
int M = str.length();
// Stores length of longest
// common prefix in Trie with str
int len = 0;
// Traverse the string str
for (int i = 0; i < M; i++) {
// If str[i] is present in
// the current path of Trie
if (root.child[str.charAt(i)] != null) {
// Update len
len++;
// Update root
root = root.child[str.charAt(i)];
}
else {
return len;
}
}
return len;
}
// Function to print the pair having maximum
// length of the longest common prefix
private static void findMaxLenPair(List<String> arr,
int N)
{
// Stores index of the string having
// maximum length of longest common prefix
int idx = -1;
// Stores maximum length of longest
// common prefix.
int len = 0;
// Create root node of Trie
TrieNode root = new TrieNode();
// Insert arr[0] into Trie
insertTrie(root, arr.get(0));
// Traverse the array.
for (int i = 1; i < N; i++) {
// Stores maximum length of longest
// common prefix in Trie with arr[i]
int temp = findStrLen(root, arr.get(i));
// If temp is greater than len
if (temp > len) {
// Update len
len = temp;
// Update idx
idx = i;
}
insertTrie(root, arr.get(i));
}
// Traverse array arr[]
for (int i = 0; i < N; i++) {
// Stores length of arr[i]
int M = arr.get(i).length();
// Check if maximum length of
// longest common prefix > M
if (i != idx && M >= len) {
boolean found = true;
// Traverse string arr[i]
// and arr[j]
for (int j = 0; j < len; j++) {
// If current character of both
// string does not match.
if (arr.get(i).charAt(j)
!= arr.get(idx).charAt(j)) {
found = false;
break;
}
}
// Print pairs having maximum length
// of the longest common prefix
if (found) {
System.out.println("(" + arr.get(i)
+ ", " + arr.get(idx)
+ ")");
return;
}
}
}
}
// Driver Code
public static void main(String[] args)
{
List<String> arr = Arrays.asList(new String[] {
"geeksforgeeks", "geeks", "geeksforcse" });
int N = arr.size();
findMaxLenPair(arr, N);
}
}
Python3
# Python3 program to implement
# the above approach
# class of Trie
class TrieNode:
def __init__(self):
self.child = dict()
# function to insert a string into trie
def insertTrie(root, string):
M = len(string) # stores string length
length = 0
for i in range(M): # traversing string
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
# Driver Code
arr = ["geeksforgeeks", "geeks", "geeksforcse"]
N = len(arr)
findMaxLenPair(arr, N)
# This code is contributed by phasing17
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
// class of Trie
public class GFG
{
public class TrieNode
{
public TrieNode[] child = new TrieNode[256];
public TrieNode() {}
};
// Function to insert a string into Trie
public static void insertTrie(TrieNode root,
String str)
{
// Stores length of the string
int M = str.Length;
// Traverse the string str
for (int i = 0; i < M; i++) {
// If str[i] is not present
// in current path of Trie
if (root.child[str[i]] == null) {
// Create a new node
// of Trie
root.child[str[i]] = new TrieNode();
}
// Update root
root = root.child[str[i]];
}
}
// Function to find the maximum length of
// longest common prefix in Trie with str
public static int findStrLen(TrieNode root, String str)
{
// Stores length of str
int M = str.Length;
// Stores length of longest
// common prefix in Trie with str
int len = 0;
// Traverse the string str
for (int i = 0; i < M; i++) {
// If str[i] is present in
// the current path of Trie
if (root.child[str[i]] != null) {
// Update len
len++;
// Update root
root = root.child[str[i]];
}
else {
return len;
}
}
return len;
}
// Function to print the pair having maximum
// length of the longest common prefix
public static void findMaxLenPair(List<string> arr,
int N)
{
// Stores index of the string having
// maximum length of longest common prefix
int idx = -1;
// Stores maximum length of longest
// common prefix.
int len = 0;
// Create root node of Trie
TrieNode root = new TrieNode();
// Insert arr[0] into Trie
insertTrie(root, arr[0]);
// Traverse the array.
for (int i = 1; i < N; i++) {
// Stores maximum length of longest
// common prefix in Trie with arr[i]
int temp = findStrLen(root, arr[i]);
// If temp is greater than len
if (temp > len) {
// Update len
len = temp;
// Update idx
idx = i;
}
insertTrie(root, arr[i]);
}
// Traverse array arr[]
for (int i = 0; i < N; i++) {
// Stores length of arr[i]
int M = arr[i].Length;
// Check if maximum length of
// longest common prefix > M
if (i != idx && M >= len) {
bool found = true;
// Traverse string arr[i]
// and arr[j]
for (int j = 0; j < len; j++) {
// If current character of both
// string does not match.
if (arr[i][j] != arr[idx][j]) {
found = false;
break;
}
}
// Print pairs having maximum length
// of the longest common prefix
if (found) {
Console.WriteLine("(" + arr[i]+ ", " + arr[idx]+ ")");
return;
}
}
}
}
// Driver Code
public static void Main()
{
List<string> arr = new List<string>() {"geeksforgeeks", "geeks", "geeksforcse" };
int N = arr.Count;
findMaxLenPair(arr, N);
}
}
// THIS CODE IS CONTRIBUTED BY SURENDRA_GANGWAR.
JavaScript
<script>
// Javascript program to implement
// the above approach
// Class of Trie
class TrieNode
{
constructor()
{
this.child = Array(256);
}
};
// Function to insert a string into Trie
function insertTrie(root, str)
{
// Stores length of the string
var M = str.length;
// Traverse the string str
for(var i = 0; i < M; i++)
{
// If str[i] is not present
// in current path of Trie
if (root.child[str[i]] == null)
{
// Create a new node
// of Trie
root.child[str[i]] = new TrieNode();
}
// Update root
root = root.child[str[i]];
}
}
// Function to find the maximum length of
// longest common prefix in Trie with str
function findStrLen(root, str)
{
// Stores length of str
var M = str.length;
// Stores length of longest
// common prefix in Trie with str
var len = 0;
// Traverse the string str
for(var i = 0; i < M; i++)
{
// If str[i] is present in
// the current path of Trie
if (root.child[str[i]] != null)
{
// Update len
len++;
// Update root
root = root.child[str[i]];
}
else
{
return len;
}
}
return len;
}
// Function to print the pair having maximum
// length of the longest common prefix
function findMaxLenPair(arr, N)
{
// Stores index of the string having
// maximum length of longest common prefix
var idx = -1;
// Stores maximum length of longest
// common prefix.
var len = 0;
// Create root node of Trie
var root = new TrieNode();
// Insert arr[0] into Trie
insertTrie(root, arr[0]);
// Traverse the array.
for(var i = 1; i < N; i++)
{
// Stores maximum length of longest
// common prefix in Trie with arr[i]
var temp = findStrLen(root, arr[i]);
// If temp is greater than len
if (temp > len)
{
// Update len
len = temp;
// Update idx
idx = i;
}
insertTrie(root, arr[i]);
}
// Traverse array arr[]
for(var i = 0; i < N; i++)
{
// Stores length of arr[i]
var M = arr[i].length;
// Check if maximum length of
// longest common prefix > M
if (i != idx && M >= len)
{
var found = true;
// Traverse string arr[i]
// and arr[j]
for(var j = 0; j < len; j++)
{
// If current character of both
// string does not match.
if (arr[i][j] != arr[idx][j])
{
found = false;
break;
}
}
// Print pairs having maximum length
// of the longest common prefix
if (found)
{
document.write("(" + arr[i] +
", " + arr[idx] + ")");
return;
}
}
}
}
// Driver Code
var arr = [ "geeksforgeeks", "geeks",
"geeksforcse" ];
var N = arr.length;
findMaxLenPair(arr, N);
// This code is contributed by rrrtnx
</script>
Output: (geeksforgeeks, geeksforcse)
Time Complexity: O(N * M), where M denotes the length of the longest string
Auxiliary Space: 0(N * 256)
Similar Reads
Length of longest common prefix possible by rearranging strings in a given array
Given an array of strings arr[], the task is to find the length of the longest common prefix by rearranging the characters of each string of the given array. Examples: Input: arr[] = {âaabdcâ, âabcdâ, âaacdâ}Output: 3Explanation: Rearrange characters of each string of the given array such that the a
8 min read
Length of longest prefix anagram which are common in given two strings
Given two strings str1 and str2 of the lengths of N and M respectively, the task is to find the length of the longest anagram string that is prefix substring of both strings. Examples: Input: str1 = "abaabcdezzwer", str2 = "caaabbttyh"Output: 6Explanation: Prefixes of length 1 of string str1 and str
8 min read
Maximize product of lengths of strings having no common characters
Given an array arr[] consisting of N strings, the task is to find the maximum product of the length of the strings arr[i] and arr[j] for all unique pairs (i, j), where the strings arr[i] and arr[j] contain no common characters. Examples: Input: arr[] = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"}
12 min read
Maximum number of Strings with Common Prefix of length K
Given a string array arr[] of length N, the task is to find the maximum number of strings that share a common prefix of length K. Examples: Input: arr = { { "hello", "heydeei", "hap", "hak", "paloa", "padfk", "padfla", "pada" } }, K = 4Output: 2Explanation: String padfk", "padfla" are the two string
8 min read
Maximum sum of lengths of a pair of strings with no common characters from a given array
Given an array arr[] consisting of N strings, the task is to find the maximum sum of length of the strings arr[i] and arr[j] for all unique pairs (i, j), where the strings arr[i] and arr[j] contains no common characters. Examples: Input: arr[] = ["abcd", "cat", "lto", "car", "wxyz", "abcdef"]Output:
7 min read
Substring of length K having maximum frequency in the given string
Given a string str, the task is to find the substring of length K which occurs the maximum number of times. If more than one string occurs maximum number of times, then print the lexicographically smallest substring. Examples: Input: str = "bbbbbaaaaabbabababa", K = 5Output: ababaExplanation:The sub
14 min read
Count pair of indices in Array having equal Prefix-MEX and Suffix-MEX
Given an array arr[] of N elements, the task is to find the number of pairs of indices such that the Prefix-MEX of the one index is equal to the Suffix-MEX of the other index. Order of indices in pair matters. MEX of an array refers to the smallest missing non-negative integer of the array. For the
10 min read
Construct an Array of Strings having Longest Common Prefix specified by the given Array
Given an integer array arr[] of size N, the task is to construct an array consisting of N+1 strings of length N such that arr[i] is equal to the Longest Common Prefix of ith String and (i+1)th String. Examples: Input: arr[] = {1, 2, 3} Output: {"abb", "aab", "aaa", "aaa"} Explanation: Strings "abb"
6 min read
Print all strings of maximum length from an array of strings
Given an array of strings arr[], the task is to print all the strings of maximum length from the given array. Example: Input: arr[] = {âabaâ, âaaâ, âadâ, âvcdâ, âabaâ}Output: aba vcd abaExplanation:Maximum length among all the strings from the given array is 3.The strings having length equal to 3 fr
7 min read
Longest palindrome formed by concatenating and reordering strings of equal length
Given an array arr[] consisting of N strings of equal length M, the task is to create the longest palindrome by concatenating the strings. Reordering and discarding some strings from the given set of strings can also be done.Examples: Input: N = 3, arr[] = { "tab", "one", "bat" }, M = 3 Output: tabb
9 min read