Maximize length of the String by concatenating characters from an Array of Strings

Given an array of strings arr[], the task is to find the maximum possible length of a string of distinct characters that can be generated by concatenating of the subsequence of the given array.

Examples:

Input: arr[] = {“ab”, “cd”, “ab”}
Output: 4
Explanation:
All possible combinations are {“”, “ab”, “cd”, “abcd”, “cdab”}.
Therefore, maximum length possible is 4.

Input: arr[] = {“abcdefgh”}
Output: 8
Explanation:
All possible combinations are: “”, “abcdefgh”.
Therefore, the maximum length possible is 8.

Approach: The idea is to use Recursion.
Follow the steps below to solve the problem:



  • Iterate from left to right and consider every string as a possible starting substring.
  • Iniatialize a HashSet to store the distinct characters encountered so far.
  • Once a string is selected as starting substring, check for every remaining string, if it only contains characters which have not occurred before. Append this string as a substring to the current string being generated.
  • After performing the above steps, print the maximum length of a string that has been generated.

Below is the implementation of the above approach:

C++

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 check if all the
// string characters are unique
bool check(string s)
{
  
    set<char> a;
  
    // Check for repetation in
    // characters
    for (auto i : s) {
        if (a.count(i))
            return false;
        a.insert(i);
    }
  
    return true;
}
  
// Funcyion to generate all possible strings
// from the given array
vector<string> helper(vector<string>& arr,
                      int ind)
{
  
    // Base case
    if (ind == arr.size())
        return { "" };
  
    // Consider every string as
    // a starting substring and
    // store the generated string
    vector<string> tmp
        = helper(arr, ind + 1);
  
    vector<string> ret(tmp.begin(),
                       tmp.end());
  
    // Add current string to result of
    // other strings and check if
    // characters are unique or not
    for (auto i : tmp) {
        string test = i + arr[ind];
        if (check(test))
            ret.push_back(test);
    }
  
    return ret;
}
  
// Function to find the maximum
// possible length of a string
int maxLength(vector<string>& arr)
{
    vector<string> tmp = helper(arr, 0);
  
    int len = 0;
  
    // Return max length possible
    for (auto i : tmp) {
        len = len > i.size()
                  ? len
                  : i.size();
    }
  
    // Return the answer
    return len;
}
  
// Driver Code
int main()
{
    vector<string> s;
    s.push_back("abcdefgh");
  
    cout << maxLength(s);
  
    return 0;
}

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to implement 
// the above approach 
using System; 
using System.Collections; 
using System.Collections.Generic; 
using System.Text; 
  
class GFG{
      
// Function to check if all the
// string characters are unique
static bool check(string s)
{
  
    HashSet<char> a = new HashSet<char>();
  
    // Check for repetation in
    // characters
    for(int i = 0; i < s.Length; i++)
    {
        if (a.Contains(s[i]))
        {
            return false;
        }
        a.Add(s[i]);
    }
    return true;
}
  
// Funcyion to generate all possible
//  strings from the given array
static ArrayList helper(ArrayList arr,
                        int ind)
{
      
    // Base case
    if (ind == arr.Count)
        return new ArrayList(){""};
  
    // Consider every string as
    // a starting substring and
    // store the generated string
    ArrayList tmp = helper(arr, ind + 1);
  
    ArrayList ret = new ArrayList(tmp);
  
    // Add current string to result of
    // other strings and check if
    // characters are unique or not
    for(int i = 0; i < tmp.Count; i++)
    {
        string test = (string)tmp[i] +
                      (string)arr[ind];
                        
        if (check(test))
            ret.Add(test);
    }
    return ret;
}
  
// Function to find the maximum
// possible length of a string
static int maxLength(ArrayList arr)
{
    ArrayList tmp = helper(arr, 0);
  
    int len = 0;
  
    // Return max length possible
    for(int i = 0; i < tmp.Count; i++)
    {
        len = len > ((string)tmp[i]).Length ? len : 
                    ((string)tmp[i]).Length;
    }
      
    // Return the answer
    return len;
}
      
// Driver Code
public static void Main(string[] args)
{
    ArrayList s = new ArrayList();
    s.Add("abcdefgh");
  
    Console.Write(maxLength(s));
}
}
  
// This code is contributed by rutvik_56

chevron_right


Output:

8

Time Complexity: O(2N)
Auxiliary Space: O(N * 2N)

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

Recommended Posts:


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.



Improved By : rutvik_56