Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Construct an Array of Strings having Longest Common Prefix specified by the given Array
Next article icon

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

Last Updated : 09 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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)



Next Article
Construct an Array of Strings having Longest Common Prefix specified by the given Array
author
costheta_z
Improve
Article Tags :
  • DSA
  • Hash
  • Mathematical
  • Strings
  • frequency-counting
  • Longest Common Prefix
Practice Tags :
  • Hash
  • Mathematical
  • Strings

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: (geek
    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 str
    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"
    6 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"
    8 min read
  • Longest Common Substring in an Array of Strings
    We are given a list of words sharing a common stem i.e the words originate from same word for ex: the words sadness, sadly and sad all originate from the stem 'sad'. Our task is to find and return the Longest Common Substring also known as stem of those words. In case there are ties, we choose the s
    7 min read
  • All possible strings of any length that can be formed from a given string
    Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples: Input: abcOutput: a b c abc ab ac bc bac bca cb ca ba cab cba acbInput: abcdOutput: a b ab ba c ac ca bc cb abc acb bac bca cab cba d ad da bd db abd adb bad bda
    10 min read
  • Minimize sum of distinct elements of all prefixes by rearranging Array
    Given an array arr[] with size N, the task is to find the minimum possible sum of distinct elements over all the prefixes of the array that can be obtained by rearranging the elements of the array. Examples: Input: arr[] = {3, 3, 2, 2, 3}, N = 5Output: 7Explanation: The permutation arr[] = {3, 3, 3,
    8 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
  • Longest palindromic string formed by concatenation of prefix and suffix of a string
    Given string str, the task is to find the longest palindromic substring formed by the concatenation of the prefix and suffix of the given string str. Examples: Input: str = "rombobinnimor" Output: rominnimor Explanation: The concatenation of string "rombob"(prefix) and "mor"(suffix) is "rombobmor" w
    11 min read
  • Longest string in an array which matches with prefix of the given string
    Given an array of strings arr[] and Q queries where each query consists of a string str, the task is to find the longest string in the array that matches with prefix of the given string str i.e. the string must be prefix of str. Examples: Input: arr[] = {"GeeksForGeeks", "GeeksForGeeksd", "Arnab", "
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences