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: 3
Explanation: Rearrange characters of each string of the given array such that the array becomes {“acdab”, “acdb”, “acda”}.
Therefore, the longest common prefix of all the strings of the given array is “acd” having length equal to 3.

Input: arr[] = {“abcdef”, “adgfse”, “fhfdd”}
Output: 2
Explanation: Rearrange characters of each string of the given array such that the array becomes {“dfcaeb”, “dfgase”, “dffhd”}.
Therefore, the longest common prefix of all the strings of the given array is “df” having length equal to 2.

Naive Approach: The simplest approach to solve this problem is to generate all possible permutations of each string of the given array and find the longest common prefix of all the strings. Finally, print the length of the longest common prefix.



Time Complexity: O(N * log M * (M!)N)
Auxiliary Space: O(M), N is the number of strings, M is the length of the longest string.

Efficient Approach: To optimize the above approach the idea is to use Hashing. Follow the steps below to solve the problem:

  • Initialize a 2D array, say freq[N][256] such that freq[i][j] stores the frequency of a character(= j) in string arr[i].
  • Traverse the given array and stores the frequency of arr[i][j] into freq[i][arr[i][j]].
  • Initialize a variable, say maxLen to store the length of the longest common prefix
  • Iterate over all possible characters and find the minimum frequency, say minRowVal of the current character in all the strings of the given array, and increment the value of maxLen by minRowVal
  • Finally, print the value of maxLen.

Below is the implementation of the above approach:

C++14

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to get the length
// of the longest common prefix
// by rearranging the strings
int longComPre(string arr[], int N)
{
    // freq[i][j]: stores the frequency
    // of a character(= j) in
    // a string arr[i]
    int freq[N][256];
 
    // Initilize freq[][] array.
    memset(freq, 0, sizeof(freq));
 
    // Traverse the given array
    for (int i = 0; i < N; i++) {
 
        // Stores length of
        // current string
        int M = arr[i].length();
 
        // Traverse current string
        // of the given array
        for (int j = 0; j < M;
             j++) {
 
            // Update the value of
            // freq[i][arr[i][j]]
            freq[i][arr[i][j]]++;
        }
    }
 
    // Stores the length of
    // longest common prefix
    int maxLen = 0;
 
    // Count the minimum frequency
    // of each character in
    // in all the strings of arr[]
    for (int j = 0; j < 256; j++) {
 
        // Stores minimum value
        // in each row of freq[][]
        int minRowVal = INT_MAX;
 
        // Calculate minimum frequency
        // of current character
        // in all the strings.
        for (int i = 0; i < N;
             i++) {
 
            // Update minRowVal
            minRowVal = min(minRowVal,
                            freq[i][j]);
        }
 
        // Update maxLen
        maxLen += minRowVal;
    }
    return maxLen;
}
 
// Driver Code
int main()
{
    string arr[] = { "aabdc",
                     "abcd",
                     "aacd" };
    int N = 3;
    cout << longComPre(arr, N);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to implement
// the above approach
import java.util.*;
class GFG{
 
// Function to get the length
// of the longest common prefix
// by rearranging the Strings
static int longComPre(String arr[],
                      int N)
{
  // freq[i][j]: stores the
  // frequency of a character(= j)
  // in a String arr[i]
  int [][]freq = new int[N][256];
 
  // Traverse the given array
  for (int i = 0; i < N; i++)
  {
    // Stores length of
    // current String
    int M = arr[i].length();
 
    // Traverse current String
    // of the given array
    for (int j = 0; j < M; j++)
    {
      // Update the value of
      // freq[i][arr[i][j]]
      freq[i][arr[i].charAt(j)]++;
    }
  }
 
  // Stores the length of
  // longest common prefix
  int maxLen = 0;
 
  // Count the minimum frequency
  // of each character in
  // in all the Strings of arr[]
  for (int j = 0; j < 256; j++)
  {
    // Stores minimum value
    // in each row of freq[][]
    int minRowVal = Integer.MAX_VALUE;
 
    // Calculate minimum frequency
    // of current character
    // in all the Strings.
    for (int i = 0; i < N; i++)
    {
      // Update minRowVal
      minRowVal = Math.min(minRowVal,
                           freq[i][j]);
    }
 
    // Update maxLen
    maxLen += minRowVal;
  }
  return maxLen;
}
 
// Driver Code
public static void main(String[] args)
{
  String arr[] = {"aabdc",
                  "abcd",
                  "aacd"};
  int N = 3;
  System.out.print(longComPre(arr, N));
}
}
 
// This code is contributed by gauravrajput1

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to implement
# the above approach
import sys
 
# Function to get the length
# of the longest common prefix
# by rearranging the strings
def longComPre(arr, N):
     
    # freq[i][j]: stores the frequency
    # of a character(= j) in
    # a arr[i]
    freq = [[0 for i in range(256)]
               for i in range(N)]
 
    # Initialize freq[][] array.
    # memset(freq, 0, sizeof(freq))
 
    # Traverse the given array
    for i in range(N):
         
        # Stores length of
        # current string
        M = len(arr[i])
 
        # Traverse current string
        # of the given array
        for j in range(M):
             
            # Update the value of
            # freq[i][arr[i][j]]
            freq[i][ord(arr[i][j])] += 1
 
    # Stores the length of
    # longest common prefix
    maxLen = 0
 
    # Count the minimum frequency
    # of each character in
    #in all the strings of arr[]
    for j in range(256):
         
        # Stores minimum value
        # in each row of freq[][]
        minRowVal = sys.maxsize
 
        # Calculate minimum frequency
        # of current character
        # in all the strings.
        for i in range(N):
             
            # Update minRowVal
            minRowVal = min(minRowVal,
                            freq[i][j])
 
        # Update maxLen
        maxLen += minRowVal
         
    return maxLen
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ "aabdc", "abcd", "aacd" ]
    N = 3
     
    print(longComPre(arr, N))
 
# This code is contributed by mohit kumar 29

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to get the length
// of the longest common prefix
// by rearranging the Strings
static int longComPre(String []arr,
                      int N)
{
  // freq[i,j]: stores the
  // frequency of a character(= j)
  // in a String arr[i]
  int [,]freq = new int[N, 256];
 
  // Traverse the given array
  for (int i = 0; i < N; i++)
  {
    // Stores length of
    // current String
    int M = arr[i].Length;
 
    // Traverse current String
    // of the given array
    for (int j = 0; j < M; j++)
    {
      // Update the value of
      // freq[i,arr[i,j]]
      freq[i, arr[i][j]]++;
    }
  }
 
  // Stores the length of
  // longest common prefix
  int maxLen = 0;
 
  // Count the minimum frequency
  // of each character in
  // in all the Strings of []arr
  for (int j = 0; j < 256; j++)
  {
    // Stores minimum value
    // in each row of [,]freq
    int minRowVal = int.MaxValue;
 
    // Calculate minimum frequency
    // of current character
    // in all the Strings.
    for (int i = 0; i < N; i++)
    {
      // Update minRowVal
      minRowVal = Math.Min(minRowVal,
                           freq[i, j]);
    }
 
    // Update maxLen
    maxLen += minRowVal;
  }
  return maxLen;
}
 
// Driver Code
public static void Main(String[] args)
{
  String []arr = {"aabdc",
                  "abcd",
                  "aacd"};
  int N = 3;
  Console.Write(longComPre(arr, N));
}
}
 
// This code is contributed by gauravrajput1

chevron_right


Output

3


Time Complexity: O(N * (M + 256))
Auxiliary Space: O(N * 256)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.