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:
Maximize product of lengths of strings having no common characters
Next article icon

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

Last Updated : 22 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Find the largest possible string of distinct characters formed using a combination of given strings. Any given string has to be chosen completely or not to be chosen at all. 

Examples:

Input: strings =”abcd”, “efgh”, “efgh” 
Output: 8
Explanation: 
All possible combinations are {“”, “abcd”, “efgh”, “abcdefgh”}. 
Therefore, maximum length possible is 8.

Input: strings = “123467890” 
Output: 10
Explanation: 
All possible combinations are: “”, “1234567890”. 
Therefore, the maximum length possible is 10. 

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.
  • Initialize 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++




// 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 repetition in
    // characters
    for (auto i : s) {
        if (a.count(i))
            return false;
        a.insert(i);
    }
 
    return true;
}
 
// Function 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;
}
 
 

Java




// Java program to implement 
// the above approach
import java.util.*;
import java.lang.*;
 
class GFG{
 
// Function to check if all the
// string characters are unique
static boolean check(String s)
{
    HashSet<Character> a = new HashSet<>();
     
    // Check for repetition in
    // characters
    for(int i = 0; i < s.length(); i++)
    {
        if (a.contains(s.charAt(i)))
        {
            return false;
        }
        a.add(s.charAt(i));
    }
    return true;
}
 
// Function to generate all possible
//  strings from the given array
static ArrayList<String> helper(ArrayList<String> arr,
                                int ind)
{
    ArrayList<String> fin = new ArrayList<>();
    fin.add("");
       
    // Base case
    if (ind == arr.size() )
        return fin;
     
    // Consider every string as
    // a starting substring and
    // store the generated string
    ArrayList<String> tmp = helper(arr, ind + 1);
     
    ArrayList<String> 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.size(); i++)
    {
        String test = tmp.get(i) +
                      arr.get(ind);
                         
        if (check(test))
            ret.add(test);
    }
    return ret;
}
 
// Function to find the maximum
// possible length of a string
static int maxLength(ArrayList<String> arr)
{
    ArrayList<String> tmp = helper(arr, 0);
     
    int len = 0;
     
    // Return max length possible
    for(int i = 0; i < tmp.size(); i++)
    {
        len = len > tmp.get(i).length() ? len : 
                    tmp.get(i).length();
    }
       
    // Return the answer
    return len;
}
 
// Driver code
public static void main (String[] args)
{
    ArrayList<String> s = new ArrayList<>();
    s.add("abcdefgh");
     
    System.out.println(maxLength(s));
}
}
 
// This code is contributed by offbeat
 
 

Python3




# Python3 program to implement
# the above approach
  
# Function to check if all the
# string characters are unique
def check(s):
     
    a = set()
  
    # Check for repetition in
    # characters
    for i in s:
        if i in a:
            return False
             
        a.add(i)
  
    return True
  
# Function to generate all possible
# strings from the given array
def helper(arr, ind):
  
    # Base case
    if (ind == len(arr)):
        return [""]
  
    # Consider every string as
    # a starting substring and
    # store the generated string
    tmp = helper(arr, ind + 1)
  
    ret = tmp
  
    # Add current string to result of
    # other strings and check if
    # characters are unique or not
    for i in tmp:
        test = i + arr[ind]
         
        if (check(test)):
            ret.append(test)
  
    return ret
     
# Function to find the maximum
# possible length of a string
def maxLength(arr):
 
    tmp = helper(arr, 0)
  
    l = 0
  
    # Return max length possible
    for i in tmp:
        l = l if l > len(i) else len(i)
  
    # Return the answer
    return l
 
# Driver Code
if __name__=='__main__':
     
    s = []
    s.append("abcdefgh")
  
    print(maxLength(s))
  
# This code is contributed by pratham76
 
 

C#




// 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 repetition in
    // characters
    for(int i = 0; i < s.Length; i++)
    {
        if (a.Contains(s[i]))
        {
            return false;
        }
        a.Add(s[i]);
    }
    return true;
}
 
// Function 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
 
 

Javascript




<script>
    // Javascript program to implement the above approach
     
    // Function to check if all the
    // string characters are unique
    function check(s)
    {
        let a = new Set();
 
        // Check for repetition in
        // characters
        for(let i = 0; i < s.length; i++)
        {
            if (a.has(s[i]))
            {
                return false;
            }
            a.add(s[i]);
        }
        return true;
    }
 
    // Function to generate all possible
    //  strings from the given array
    function helper(arr, ind)
    {
        let fin = [];
        fin.push("");
 
        // Base case
        if (ind == arr.length)
            return fin;
 
        // Consider every string as
        // a starting substring and
        // store the generated string
        let tmp = helper(arr, ind + 1);
 
        let ret = tmp;
 
        // Add current string to result of
        // other strings and check if
        // characters are unique or not
        for(let i = 0; i < tmp.length; i++)
        {
            let test = tmp[i] + arr[ind];
 
            if (check(test))
                ret.push(test);
        }
        return ret;
    }
 
    // Function to find the maximum
    // possible length of a string
    function maxLength(arr)
    {
        let tmp = helper(arr, 0);
 
        let len = 0;
 
        // Return max length possible
        for(let i = 0; i < tmp.length; i++)
        {
            len = len > tmp[i].length ? len : tmp[i].length;
        }
 
        // Return the answer
        return len;
    }
     
    let s = [];
    s.push("abcdefgh");
      
    document.write(maxLength(s));
 
// This code is contributed by suresh07.
</script>
 
 
Output
8

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

Efficient Approach (Using Dynamic Programming): 

C++




#include <bits/stdc++.h>
using namespace std;
 
int maxLength(vector<string>& A)
{
    vector<bitset<26> > dp
        = { bitset<26>() }; // auxiliary dp storage
    int res = 0; // will store number of unique chars in
                 // resultant string
    for (auto& s : A) {
        bitset<26> a; // used to track unique chars
        for (char c : s)
            a.set(c - 'a');
        int n = a.count();
        if (n < s.size())
            continue; // duplicate chars in current string
 
        for (int i = dp.size() - 1; i >= 0; --i) {
            bitset<26> c = dp[i];
            if ((c & a).any())
                continue; // if 1 or more char common
            dp.push_back(c | a); // valid concatenation
            res = max(res, (int)c.count() + n);
        }
    }
    return res;
}
 
int main()
{
    vector<string> v = { "ab", "cd", "ab" };
    int ans = maxLength(v);
    cout << ans; // resultant answer string : cfbdghzest
    return 0;
}
 
 

Java




import java.util.*;
 
public class Main {
    public static int maxLength(String[] A)
    {
        List<Set<Character> > dp
            = new ArrayList<>(Arrays.asList(
                new HashSet<>())); // auxiliary dp storage
        int res = 0; // will store number of unique chars in
                     // resultant string
        for (String s : A) {
            Set<Character> a = new HashSet<>();
            for (char c : s.toCharArray())
                a.add(c);
            if (a.size() < s.length())
                continue; // duplicate chars in current
                          // string
 
            for (int i = dp.size() - 1; i >= 0; --i) {
                Set<Character> c = new HashSet<>(dp.get(i));
                if (!Collections.disjoint(a, c))
                    continue; // if 1 or more char common
                dp.add(new HashSet<>(c));
                dp.get(dp.size() - 1)
                    .addAll(a); // valid concatenation
                res = Math.max(res, c.size() + a.size());
            }
        }
        return res;
    }
 
    public static void main(String[] args)
    {
        String[] v = { "ab", "cd", "ab" };
        int ans = maxLength(v);
        System.out.println(
            ans); // resultant answer string : cfbdghzest
    }
}
 
 

Python3




# Python program to implement the above approach
def maxLength(A):
    # Initialize an empty list to store bitsets (each representing a unique set of characters)
    # We start with an empty bitset, so that we can use it to compare with the incoming bitsets
    dp = [set()]  # auxiliary dp storage
    res = 0  # will store number of unique chars in
    # resultant string
    for s in A:
        a = set(s)  # used to track unique chars
        if len(a) < len(s):
            continue  # duplicate chars in current string
 
        for i in range(len(dp)-1, -1, -1):
            c = dp[i]
            if a & c:
                continue  # if 1 or more char common
            dp.append(c | a)  # valid concatenation
            res = max(res, len(c) + len(a))
    return res
 
 
v = ["ab", "cd", "ab"]
ans = maxLength(v)
print(ans) 
 
# Contributed by adityasha4x71
 
 

Javascript




// javascript code implemementation
 
function maxLength(A)
{
    let dp = new Array(26);
    for(let i = 0; i < 26; i++){
        dp[i] = new Array(26).fill(0); // auxiliary dp storage
    }
 
    let res = 0; // will store number of unique chars in
                 // resultant string
 
    for(let i = 0; i < A.length; i++){
        let s = A[i];
         
        let a = [];
        for(let j = 0; j < s.length; j++){
            a[s[j].charCodeAt(0) - 97] = "1";
        }
         
        let n = 0;
        for(let j = 0; j < a.length; j++){
            if(a[j] == "1") n = n + 1;
        }
         
        if(n < s.length) continue; // duplicate chars in current string
         
        for (let j = dp.length - 1; j >= 0; --j) {
            let c = dp[j];
 
            for(let k = 0; k < 26; k++){
                if(c[k] == "1" && a[k] == "1") continue; // if 1 or more char common
            }
             
            let temp = "";
            for(let k = 0; k < 26; k++){
                if(c[k] == "1" || a[k] == "1") temp = temp + "1";
                else temp = temp + "0";
            }
            dp.push(temp); // valid concatenation
            let c_count = 0;
            for(let k = 0; k < 26; k++){
                if(c[k] == "1") c_count++;
            }
            res = Math.max(res, c_count + n-2);
        }
    }
 
    return res;
}
 
 
let v = [ "ab", "cd", "ab" ];
let ans = maxLength(v);
console.log(ans); // resultant answer string : cfbdghzest
 
// The code is contributed by Arushi Jindal.
 
 

C#




// C# code implemementation
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
 
class HelloWorld {
     
    public static int maxLength(string[] A)
    {
        List<string> dp = new List<string> ();
        for(int i = 0; i < 26; i++){
            string temp = "";
            for(int j = 0; j < 26; j++){
                temp = temp + "0";
            }
            dp.Add(temp);
        }
 
         
        int res = 0; // will store number of unique chars in
                     // resultant string
 
        for(int i = 0; i < A.Length; i++){
            string s = A[i];
            List<char> a = new List<char>();
            for(int indx = 0; indx < 26; indx++){
                a.Add('0');
            }
            for(int j = 0; j < s.Length; j++){
                a[System.Convert.ToInt32(s[j]) - 97] = '1';
            }
 
            int n = 0;
            for(int j = 0; j < a.Count; j++){
                if(a[j] == '1') n = n + 1;
            }
 
            if(n < s.Length) continue; // duplicate chars in current string
 
            for (int j = dp.Count - 1; j >= 0; --j) {
                string c = dp[j];
 
                for(int k = 0; k < 26; k++){
                    if(c[k] == '1' && a[k] == '1') continue; // if 1 or more char common
                }
 
                string temp = "";
                for(int k = 0; k < 26; k++){
                    if(c[k] == '1' || a[k] == '1') temp = temp + "1";
                    else temp = temp + "0";
                }
                dp.Add(temp); // valid concatenation
                int c_count = 0;
                for(int k = 0; k < 26; k++){
                    if(c[k] == '1') c_count++;
                }
                res = Math.Max(res, c_count + n-2);
            }
        }
 
        return res;
    }
    static void Main() {
        string[] v = {"ab", "cd", "ab"};
        int ans = maxLength(v);
        Console.WriteLine(ans); // resultant answer string : cfbdghzest
    }
}
 
// The code is contributed by Nidhi goel.
 
 
Output
4

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



Next Article
Maximize product of lengths of strings having no common characters
author
rishabhtyagi2306
Improve
Article Tags :
  • Arrays
  • DSA
  • Hash
  • Mathematical
  • Recursion
  • Strings
  • HashSet
  • subsequence
  • substring
Practice Tags :
  • Arrays
  • Hash
  • Mathematical
  • Recursion
  • Strings

Similar Reads

  • Smallest string containing all unique characters from given array of strings
    Given an array of strings arr[], the task is to find the smallest string which contains all the characters of the given array of strings. Examples: Input: arr[] = {"your", "you", "or", "yo"}Output: ruyoExplanation: The string "ruyo" is the smallest string which contains all the characters that are u
    9 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
  • Maximum sum of lengths of a pair of strings with no common characters from a given array
    Given an array arr[] consisting of N strings, the task is to find the maximum sum of length of the strings arr[i] and arr[j] for all unique pairs (i, j), where the strings arr[i] and arr[j] contains no common characters. Examples: Input: arr[] = ["abcd", "cat", "lto", "car", "wxyz", "abcdef"]Output:
    7 min read
  • Maximize product of lengths of strings having no common characters
    Given an array arr[] consisting of N strings, the task is to find the maximum product of the length of the strings arr[i] and arr[j] for all unique pairs (i, j), where the strings arr[i] and arr[j] contain no common characters. Examples: Input: arr[] = {"abcw", "baz", "foo", "bar", "xtfn", "abcdef"}
    12 min read
  • Length of the smallest sub-string consisting of maximum distinct characters
    Given a string of length N, find the length of the smallest sub-string consisting of maximum distinct characters. Note : Our output can have same character.  Examples:  Input : "AABBBCBB"Output : 5Input : "AABBBCBBAC"Output : 3Explanation : Sub-string -> "BAC"Input : "GEEKSGEEKSFOR"Output : 8Expl
    15+ min read
  • Maximize characters to be removed from string with given condition
    Given a string s. The task is to maximize the removal of characters from s. Any character can be removed if at least one of its adjacent characters is the previous letter in the Latin English alphabet. Examples: Input: s = "bacabcab"Output: 4Explanation: Following are the removals that maximize the
    6 min read
  • Pairs of strings which on concatenating contains each character of "string"
    Given an array of strings arr[]. The task is to find the count of unordered pairs of strings (arr[i], arr[j]), which in concatenation includes each character of the string "string" at least once. Examples: Input: arr[] = { "s", "ng", "stri"} Output: 1 (arr[1], arr[2]) is the only pair which on conca
    9 min read
  • Count characters to be shifted from the start or end of a string to obtain another string
    Given two strings A and B where string A is an anagram of string B. In one operation, remove the first or the last character of the string A and insert at any position in A. The task is to find the minimum number of such operations required to be performed to convert string A into string B. Examples
    6 min read
  • Print all strings of maximum length from an array of strings
    Given an array of strings arr[], the task is to print all the strings of maximum length from the given array. Example: Input: arr[] = {“aba”, “aa”, “ad”, “vcd”, “aba”}Output: aba vcd abaExplanation:Maximum length among all the strings from the given array is 3.The strings having length equal to 3 fr
    7 min read
  • Maximum count of sub-strings of length K consisting of same characters
    Given a string str and an integer k. The task is to count the occurrences of sub-strings of length k that consist of the same characters. There can be multiple such sub-strings possible of length k, choose the count of the one which appears the maximum number of times as the sub-string (non-overlapp
    6 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