The Wayback Machine - https://web.archive.org/web/20241119202531/https://www.geeksforgeeks.org/length-of-longest-common-prefix-possible-by-rearranging-strings-in-a-given-array/
Open In App

Length of longest common prefix possible by rearranging strings in a given array

Last Updated : 09 Aug, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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




// 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];
 
    // Initialize 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);
}


Java




// 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


Python3




# 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


C#




// 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


Javascript




<script>
// Javascript program to implement
// the above approach
 
// Function to get the length
// of the longest common prefix
// by rearranging the Strings
function longComPre(arr, N)
{
 
    // freq[i][j]: stores the
  // frequency of a character(= j)
  // in a String arr[i]
  let freq = new Array(N);
  for(let i = 0; i < N; i++)
  {
      freq[i] = new Array(256);
    for(let j = 0; j < 256; j++)
    {
        freq[i][j] = 0;
    }
     
  }
  
  // Traverse the given array
  for (let i = 0; i < N; i++)
  {
    // Stores length of
    // current String
    let M = arr[i].length;
  
    // Traverse current String
    // of the given array
    for (let j = 0; j < M; j++)
    {
     
      // Update the value of
      // freq[i][arr[i][j]]
      freq[i][arr[i][j].charCodeAt(0)]++;
    }
  }
  
  // Stores the length of
  // longest common prefix
  let maxLen = 0;
  
  // Count the minimum frequency
  // of each character in
  // in all the Strings of arr[]
  for (let j = 0; j < 256; j++)
  {
   
    // Stores minimum value
    // in each row of freq[][]
    let minRowVal = Number.MAX_VALUE;
  
    // Calculate minimum frequency
    // of current character
    // in all the Strings.
    for (let i = 0; i < N; i++)
    {
      // Update minRowVal
      minRowVal = Math.min(minRowVal,
                           freq[i][j]);
    }
  
    // Update maxLen
    maxLen += minRowVal;
  }
  return maxLen;
}
 
// Driver Code
let arr= ["aabdc",
       "abcd",
       "aacd"];
let N = 3;
document.write(longComPre(arr, N));   
 
// This code is contributed by patel2127
</script>


Output

3

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



Previous Article
Next Article

Similar Reads

Pair of strings having longest common prefix of maximum length in given array
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
15+ 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 str2 are "a", and "c".Prefixes of length 2 of string
8 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" and "aab" have a single character "a" as Longest C
6 min read
Largest palindromic string possible from given strings by rearranging the characters
Given two strings S and P, the task is to find the largest palindrome possible string by choosing characters from the given strings S and P after rearranging the characters. Note: If many answers are possible, then find the lexicographically smallest T with maximum length. Examples: Input: S = "abad", T = "eeff"Output: aefbfeaExplanation: From the
13 min read
Find the longest common prefix between two strings after performing swaps on second string
Given two strings [Tex]a [/Tex]and [Tex]b [/Tex]. Find the longest common prefix between them after performing zero or more operations on string [Tex]b [/Tex]. In each operation, you can swap any two letters.Examples: Input : a = "here", b = "there" Output : 4 The 2nd string can be made "heret" by just swapping characters and thus the longest prefi
6 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 that share the common prefix of length k. Input:
8 min read
Queries to find the length of the longest prefix from given array having all elements divisible by K
Given an array arr[] consisting of N elements and an arrayQ[], the task for each query is to find the length of the longest prefix such that all the elements of this prefix are divisible by K. Examples: Input: arr[] = {12, 6, 15, 3, 10}, Q[] = {4, 3, 2}Output: 1 4 2Explanation: Q[0] = 4: arr[0] (= 12) is divisible by 4. arr[1] is not divisible by 4
10 min read
Count of strings whose prefix match with the given string to a given length k
Given an array of strings arr[] and given some queries where each query consists of a string str and an integer k. The task is to find the count of strings in arr[] whose prefix of length k matches with the k length prefix of str.Examples: Input: arr[] = {"abba", "abbb", "abbc", "abbd", "abaa", "abca"}, str = "abbg", k = 3 Output: 4 "abba", "abbb",
15+ min read
Largest Roman Numeral possible by rearranging characters of a given string
Given a string S of length N, the task is to print the highest roman number possible by rearranging the characters of the given string, if the given string is a valid roman number. If found to be not possible, then print "Invalid". Examples: Input: S = "MCMIV"Output: MMCVIExplanation: The given string S is valid Roman numeral. Rearranging character
12 min read
Minimum difference possible between two given numbers by rearranging their digits in the same order
Given two N-digit positive integers X and Y, the task is to find the minimum absolute difference between both the integers possible by rearranging the digits of both the integers in the same order. Examples: Input: X = 5181, Y = 3663Output: 1482Explanation:Rearranging the digits of both the given integers in the order of (3, 2, 4, 1) modifies the v
11 min read
Longest Common Prefix using Linked List
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”} Output : "gee" Input : {"apple", "ape", "april"} Output : "ap" Previous Approaches: Word by Word Matching, Character by Character Matching, Divide and Conquer, Binary Search, Using Trie Data Structure Below is an algorithm to solve
14 min read
Longest Common Prefix Matching | Set-6
Given a set of strings, find the longest common prefix. Examples: Input: str[] = {geeksforgeeks, geeks, geek, geezer} Output: gee Input: str[] = {apple, ape, april} Output: ap Previous Approaches: Set1 | Set2 | Set3 | Set4 | Set5 Approach: Sort the given set of N strings.Compare the first and last string in the sorted array of strings.The string wi
6 min read
Find minimum shift for longest common prefix
You are given two strings str1 and str2 of the same length. In a single shift, you can rotate one string (str2) by 1 element such that its 1st element becomes the last and the second one becomes the first like "abcd" will change to "bcda" after the one-shift operation. You have to find the minimum shift operation required to get the common prefix o
7 min read
Javascript Program To Find Longest Common Prefix Using Sorting
Problem Statement: Given a set of strings, find the longest common prefix.Examples: Input: {"geeksforgeeks", "geeks", "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", "ze
2 min read
Javascript Program To Find Longest Common Prefix Using Word By Word Matching
Given a set of strings, find the longest common prefix. Examples: Input : {“geeksforgeeks”, “geeks”, “geek”, “geezer”}Output : "gee"Input : {"apple", "ape", "april"}Output : "ap"We start with an example. Suppose there are two strings- “geeksforgeeks” and “geeks”. What is the longest common prefix in both of them? It is “geeks”.Now let us introduce
3 min read
Longest Common Prefix using Sorting
Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return “”. Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: “gee”Explanation: “gee” is the longest common prefix in all the given strings: “ge
5 min read
Longest Common Prefix
Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return “”. Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: “gee”Explanation: “gee” is the longest common prefix in all the given strings: “ge
5 min read
Longest Common Prefix using Binary Search
Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "". Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: "gee"Explanation: "gee" is the longest common prefix in all the given strings: "ge
8 min read
Longest Common Prefix using Trie
Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return “”. Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: “gee”Explanation: “gee” is the longest common prefix in all the given strings: “ge
7 min read
Longest Common Prefix using Word by Word Matching
Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "". Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: "gee"Explanation: “gee” is the longest common prefix in all the given strings: "ge
5 min read
Longest Common Prefix using Character by Character Matching
Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "". Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: "gee"Explanation: “gee” is the longest common prefix in all the given strings: "ge
5 min read
Longest Common Prefix using Divide and Conquer Algorithm
Given an array of strings arr[], the task is to return the longest common prefix among each and every strings present in the array. If there’s no prefix common in all the strings, return "". Examples: Input: arr[] = [“geeksforgeeks”, “geeks”, “geek”, “geezer”]Output: "gee"Explanation: "gee" is the longest common prefix in all the given strings: "ge
7 min read
Maximize length of longest non-decreasing array possible by the elements present in either ends of the given array
Given an array A[] of size N, the task is to find the maximum length of the longest non-decreasing array that can be generated from the given array by appending elements from either of the ends of the given array to the end of the resultant array and removing the appended element one by one. Examples: Input: A[] = {5, 6, 8, 7} Output:: 4 Explanatio
11 min read
Counting common prefix/suffix strings in two lists
Given two Lists of strings s1 and s2, you have to count the number of strings in s2 which is either a suffix or prefix of at least one string of s1. Examples: Input: s1 = ["cat", "catanddog", "lion"], s2 = ["cat", "dog", "rat"]Output: 2Explanation: String "cat" of s2 is a prefix of "catanddog"string "dog" of s2 is suffix of "catanddog" Input: s1 =
4 min read
Maximum common prefix of all strings
Given array A[] of strings of size N, the task for this problem is to print the Maximum Common prefix of string 'i' with other strings from 1 to N apart from 'i' itself for all given strings from 1 to N. Given strings consists of lowercase English letters. Examples: Input: {"abc", "abb", "aac"}Output: 2 2 1Explanation: Answer for first string is tw
12 min read
Longest palindromic string possible by concatenating strings from a given array
Given an array of strings S[] consisting of N distinct strings of length M. The task is to generate the longest possible palindromic string by concatenating some strings from the given array. Examples: Input: N = 4, M = 3, S[] = {"omg", "bbb", "ffd", "gmo"}Output: omgbbbgmoExplanation: Strings "omg" and "gmo" are reverse of each other and "bbb" is
8 min read
Maximize sum of given array by rearranging array such that the difference between adjacent elements is atmost 1
Given an array arr[] consisting of N positive integers, the task is to maximize the sum of the array element such that the first element of the array is 1 and the difference between the adjacent elements of the array is at most 1 after performing the following operations: Rearrange the array elements in any way.Reduce any element to any number that
7 min read
Split given Array in minimum number of subarrays such that rearranging the order of subarrays sorts the array
Given an array arr[] consisting of N integers, the task is to find the minimum number of splitting of array elements into subarrays such that rearranging the order of subarrays sorts the given array. Examples: Input: arr[] = {6, 3, 4, 2, 1}Output: 4Explanation:The given array can be divided into 4 subarrays as {6}, {3, 4}, {2}, {1} and these subarr
7 min read
Maximize the sum of modified values after rearranging given array based on condition array
Given a binary array arr1[] and an integer array arr2[], each of length N, the task is to rearrange the elements in the array arr2 such that the total cost generated is maximized. The total cost generated is calculated by summation of modified values in the arr2 array. The values are modified in such a way that an integer corresponding to the value
7 min read
Longest string which is prefix string of at least two strings
Given a set of strings of the same length, we need to find the length of the longest string, which is a prefix string of at least two strings. Examples: Input: ["abcde", "abcsd", "bcsdf", "abcda", "abced"] Output: 4 Explanation: Longest prefix string is "abcd". Input: ["pqrstq", "pwxyza", "abcdef", "pqrstu"] Output: 5 Approach: Starting from the 0t
6 min read
three90RightbarBannerImg