The maximum length of string formed by concatenation having an even frequency of each character


Concatenation is an operator which is used to join one or more than one string to originate a new string which would be a combination of strings that were used to generate it with the help of concatenation. In the following article, we will take the uppercase letters only in the input string.

Concatenation is an operator which is used to join one or more than one string to originate a new string which would be a combination of strings that were used to generate it with the help of concatenation. In the following article, we will take the uppercase letters only in the input string.

Let’s try to understand this problem with the help of some examples.

Input

"FEFEE", "EFF", "HGG", "AD", "HHH"

Explanation − In this example, we can see that the maximum length of string which can be formed by concatenation having an even frequency of each character is “FEFEEEFFHGGHHH” and the string we get has a length of 14. Thus, ‘14’ is the final output.

  • Frequency of F− 4

  • Frequency of E− 4

  • Frequency of H− 4

  • Frequency of G− 2

Input

"ABCD", "AVP", "ADDDC", "BCCCA", "HH", "CA"

Output

18

Explanation − In this example, we can see that the maximum length of string which can be formed by concatenation having an even frequency of each character is “ABCDADDDCBCCCAHHCA” and the string we get has a length of 18. Thus, ‘18’ is the final output.

  • Frequency of A: 4

  • Frequency of B: 2

  • Frequency of C: 6

  • Frequency of D: 4

  • Frequency of H: 2

Problem Explanation

Let’s try to understand the problem and find its solution. In the following article, we will discuss the approach to find the maximum length of string formed by concatenation having an even frequency of each character of the strings from the given array of strings. The solution will involve recursion and backtracking. For each string in the array, we will have two choices - either to include it into our final string having an even frequency of each character or we would not include that string.

So, the approach involves creating a recursive function and calling it recursively twice for each string - one after including it and another without including it. After including each string, keep checking whether all the characters in the final string have an even frequency, and keep updating the maximum length of a string having an even frequency of each character formed by concatenation.

Recursive Algorithm

  • Make a recursive function with the base case as when the index would be equal to the size of the array, the function will return. Now, in that function, we will take two cases, in the first case, we would not include the current string and make the recursive call.

  • While in the second case, we would include it and then check if the present output string matches the requirements by using another function (CheckValid), that is, it is having even frequency of each character or not

  • If yes, we will store the length of that string if it is greater than the previous size.

  • Next, we will make another recursive call in which we will include the present string.

  • This way, we will reach the final output size.

Example

The following are implementations of the above approach in various programming languages −

#include <stdio.h>
#include <string.h>
#include <stdbool.h>
// Function to check whether the string has an even frequency of each character or not
bool CheckValid(const char *str){
   // Declare a frequency array that would work like a map to store the count of each alphabet
   int mapArray[26] = { 0 };
   // Store the frequency of each alphabet, we will take uppercase English alphabets only in our string
   for (int i = 0; i < strlen(str); i++) {
      mapArray[str[i] - 'A']++;
   }
   // Check if the frequency of any alphabet is odd, if yes return false
   for (int i = 0; i < 26; i++) {
      if (mapArray[i] % 2 == 1) {
         return false;
      }
   }
   // If we have all our alphabets in even count, we can return true
   return true;
}
// Function to find the maximum length of a string having an even frequency of each character formed by concatenation
void FindMaxLength(const char *array[], int i, int size, const char *s, int* maxi){
   // Check if we have taken all strings from our array that is check the base case
   if (i == size) {
      return;
   }
   // Do not Include the string
   FindMaxLength(array, i + 1, size, s, maxi);
   // Include the string
   char combined[100]; // Choose a reasonable maximum length for your combined string
   strcpy(combined, s);
   strcat(combined, array[i]);

   if (CheckValid(combined)) {
      int currentLength = strlen(combined);
      if (currentLength > *maxi) {
         *maxi = currentLength;
      }
   }

   FindMaxLength(array, i + 1, size, combined, maxi);
}
int main(){
   // Size of the string provided by the user
   int size = 5;
   // String provided by the user
   const char* array[5] = { "FEFEE", "EFF", "HGG", "AD", "HHH" };
   // Declare a variable to store the maximum length of string formed by concatenation having even frequency of each character
   int maxi = 0;
   // Call the function to find the maximum length of string formed by concatenation having an even frequency of each character
   FindMaxLength(array, 0, size, "", &maxi);
   // Print the final output
   printf("The maximum length of string formed by concatenation having an even frequency of each character is: %d", maxi);
   return 0;
}

Output

The maximum length of string formed by concatenation having an even frequency of each character is: 14
#include <bits/stdc++.h>
using namespace std;
// Function to check whether the string has an even frequency of each character or not
bool CheckValid(string str){
   // Declare a frequency array that would work like a map to store the count of each alphabet
   int mapArray[26] = { 0 };
   // Store the frequency of each alphabet, we will take uppercase English alphabets only in our string
   for (int i = 0; i < str.length(); i++) {
      mapArray[str[i] - 'A']++;
   }
   // Check if the frequency of any alphabet is odd, if yes return false
   for (int i = 0; i < 26; i++) {
      if (mapArray[i] % 2 == 1) {
         return false;
      }
   }
   // If we have all our alphabets in even count, we can return true
   return true;
}
// Function to find the maximum length of a string having an even frequency of each character formed by concatenation
void FindMaxLength(string array[], int i, int size, string s, int& maxi){
   // Check if we have taken all strings from our array that is check the base case
   if (i == size) {
      return;
   }
   // Do not Include the string
   FindMaxLength(array, i + 1, size, s, maxi);
   // Include the string
   s += array[i];
   // Check if the string collected is giving us a string with all character counts as even, constituted in it
   if(CheckValid(s)) {
      // Store the maximum of the previous and current length
      if(s.length() > maxi) {
         maxi = s.length();
      }
   }
   FindMaxLength(array, i + 1, size, s, maxi);
}
int main(){
   // Size of the string provided by the user
   int size = 5;
   // String provided by the user
   string array[5] = { "FEFEE", "EFF", "HGG", "AD", "HHH" };
   // Declare a variable to store the maximum length of string formed by concatenation having even frequency of each character
   int maxi = 0;
   // Call the function to find the maximum length of string formed by concatenation having an even frequency of each character
   FindMaxLength(array, 0, size, "", maxi);
   // Print the final output
   cout << "The maximum length of string formed by concatenation having an even frequency of each character is: "<< maxi <<endl;
   return 0;
}

Output

The maximum length of string formed by concatenation having an even frequency of each character is: 14
public class Main {
   public static boolean CheckValid(String str) {
      // Declare a frequency array that would work like a map to store the count of each alphabet
      int[] mapArray = new int[26];
      // Store the frequency of each alphabet, we will take uppercase English alphabets only in our string
      for (int i = 0; i < str.length(); i++) {
         mapArray[str.charAt(i) - 'A']++;
      }
      // Check if the frequency of any alphabet is odd, if yes return false
      for (int i = 0; i < 26; i++) {
         if (mapArray[i] % 2 == 1) {
            return false;
         }
      }
      // If we have all our alphabets in even count, we can return true
      return true;
   }
   //Function to find the maximum length of a string having an even frequency of each character formed by concatenation
   public static void FindMaxLength(String[] array, int i, int size, String s, int[] maxi) {
      // Check if we have taken all strings from our array that is check the base case
      if (i == size) {
         return;
      }
      FindMaxLength(array, i + 1, size, s, maxi);

      s += array[i];

      if (CheckValid(s)) {
         int currentLength = s.length();
         // Store the maximum of the previous and current length
         if (currentLength > maxi[0]) {
            maxi[0] = currentLength;
         }
      }

      FindMaxLength(array, i + 1, size, s, maxi);
   }

   public static void main(String[] args) {
      int size = 5;
      String[] array = { "FEFEE", "EFF", "HGG", "AD", "HHH" };
      int[] maxi = { 0 };

      FindMaxLength(array, 0, size, "", maxi);

      System.out.println("The maximum length of a string formed by concatenation having an even frequency of each character is: " + maxi[0]);
   }
}

Output

The maximum length of a string formed by concatenation having an even frequency of each character is: 14
# Function to check whether the string has an even frequency of each character or not
def CheckValid(s):
   # Declare a frequency array that would work like a map to store the count of each alphabet
   mapArray = [0] * 26
   # Store the frequency of each alphabet; we will take uppercase English alphabets only in our string
   for char in s:
      if 'A' <= char <= 'Z':
         mapArray[ord(char) - ord('A')] += 1

   # Check if the frequency of any alphabet is odd; if yes, return False
   for count in mapArray:
      if count % 2 == 1:
         return False

   # If we have all our alphabets in even count, we can return True
   return True

# Function to find the maximum length of a string having an even frequency of each character formed by concatenation
def FindMaxLength(array, i, size, s, maxi):
   # Check if we have taken all strings from our array, that is, check the base case
   if i == size:
      return
   # Do not include the string
   FindMaxLength(array, i + 1, size, s, maxi)
    
   # Include the string
   s += array[i]
    
   # Check if the string collected is giving us a string with all character counts as even, constituted in it
   if CheckValid(s):
      # Store the maximum of the previous and current length
      if len(s) > maxi[0]:
         maxi[0] = len(s)
    
   FindMaxLength(array, i + 1, size, s, maxi)

if __name__ == "__main__":
   size = 5
   # String provided by the user
   array = ["FEFEE", "EFF", "HGG", "AD", "HHH"]
   # Declare a variable to store the maximum length of string formed by concatenation having even frequency of each character
   maxi = [0]
   # Call the function to find the maximum length of string formed by concatenation having an even frequency of each character
   FindMaxLength(array, 0, size, "", maxi)
   # Print the final output
   print("The maximum length of a string formed by concatenation having an even frequency of each character is:", maxi[0])

Output

The maximum length of a string formed by concatenation having an even frequency of each character is: 14

Complexities for the Above Code

  • Time complexity − O(n * m * (2^n))); where ‘n’ is the length of the array that is the total number of strings given and ‘m’ is the length of the longest string present in the array. Each string will be executed twice in the recursive call making the time complexity of that recursive function ‘2^ n’ while the CheckValid function will take the total time of the size of the maximum length of the string formed by concatenation and it could vary up to (n * m), that is the case when we will include each string contained in given array in our final answer.

  • Space complexity − O(1); We have not stored any variable in some data structure in the above code.

Conclusion

In this article, to find the maximum length of string formed by concatenation having even frequency of each character. We understood the approach by using concepts like recursion and backtracking. However, the time complexity of the code given above is huge so the code would work only within some prohibited constraints when the size of string and array will have a limit.

Updated on: 05-Feb-2024

44 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements