Find smallest string with whose characters all given Strings can be generated

17 Jan, 2022
Given an array of strings arr[]. The task is to generate the string which contains all the characters of all the strings present in array and smallest in size. There can be many such possible strings and any one is acceptable.
Examples:
Input: arr[] = {“your”, “you”, “or”, “yo”}Output: ruyoExplanation: The string “ruyo” is the string which contains all the characters present in all the strings in arr[].There can be many other strings of size 4 e.g. “oury”. Those are also acceptable.
Input: arr[] = {“abm”, “bmt”, “cd”, “tca”}Output: abctdm
Approach: This problem can be solved by using the Set Data Structure. Set has the capability to remove duplicates, which is needed in this problem in order to minimize the string size. Add all the characters in the set from all the strings in the array arr[] and form a string containing all the characters remaining in the set, which is the required answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ code for the above approach#include <bits/stdc++.h>using namespace std; string minSubstr(vector<string> s){       // Stores the concatenated string    // of all the given strings    string str = "";     // Loop to iterate through all    // the given strings    for (int i = 0; i < s.size(); i++)    {        str += s[i];    }     // Set to store the characters    unordered_set<char> set;     // Loop to iterate over all    // the characters in str    for (int i = 0; i < str.length(); i++)    {        set.insert(str[i]);    }    string res = "";       // Loop to iterate over the set    for (auto itr = set.begin(); itr != set.end(); itr++)    {        res = res + (*itr);    }     // Return Answer    return res;} // Driver Codeint main(){    vector<string> arr = {"your", "you",                          "or", "yo"};     cout << (minSubstr(arr));    return 0;} // This code is contributed by Potta Lokesh
// Java program to implement above approachimport java.util.*; public class GfG {    public static String minSubstr(String s[])    {        // Stores the concatenated string        // of all the given strings        String str = "";         // Loop to iterate through all        // the given strings        for (int i = 0; i < s.length; i++) {            str += s[i];        }         // Set to store the characters        Set<Character> set =            new HashSet<Character>();         // Loop to iterate over all        // the characters in str        for (int i = 0; i < str.length();             i++) {            set.add(str.charAt(i));        }         // Stores the required answer        String res = "";        Iterator<Character> itr =            set.iterator();         // Loop to iterate over the set        while (itr.hasNext()) {            res += itr.next();        }         // Return Answer        return res;    }     // Driver Code    public static void main(String[] args)    {        String arr[]            = new String[] { "your", "you",                            "or", "yo" };         System.out.println(minSubstr(arr));    }}
# Python program to implement above approachdef minSubstr(s):       # Stores the concatenated string    # of all the given strings    str = "";     # Loop to iterate through all    # the given strings    for i in range(len(s)):        str += s[i];     # Set to store the characters    setv = set();     # Loop to iterate over all    # the characters in str    for i in range(len(str)):        setv.add(str[i]);     # Stores the required answer    res = "";     # Loop to iterate over the set    for itr in setv:        res += itr;     # Return Answer    return res; # Driver Codeif __name__ == '__main__':    arr = ["your", "you", "or", "yo"];     print(minSubstr(arr)); # This code is contributed by 29AjayKumar
// C# program to implement above approachusing System;using System.Collections.Generic; public class GfG {  public static String minSubstr(String []s)  {         // Stores the concatenated string    // of all the given strings    String str = "";     // Loop to iterate through all    // the given strings    for (int i = 0; i < s.Length; i++) {      str += s[i];    }     // Set to store the characters    HashSet<char> set =      new HashSet<char>();     // Loop to iterate over all    // the characters in str    for (int i = 0; i < str.Length;         i++) {      set.Add(str[i]);    }     // Stores the required answer    String res = "";    // Loop to iterate over the set    foreach (char itr in set) {      res += itr;    }     // Return Answer    return res;  }   // Driver Code  public static void Main(String[] args)  {    String []arr      = new String[] { "your", "you",                      "or", "yo" };     Console.WriteLine(minSubstr(arr));  }} // This code is contributed by 29AjayKumar
<script>// javascript program to implement above approachpublic class GfG{    function minSubstr(s)    {             // Stores the concatenated string        // of all the given strings        var str = "";         // Loop to iterate through all        // the given strings        for (var i = 0; i < s.length; i++) {            str += s[i];        }         // Set to store the characters        var set = new Set();         // Loop to iterate over all        // the characters in str        for (var i = 0; i < str.length;             i++) {            set.add(str.charAt(i));        }         // Stores the required answer        var res = "";         // Loop to iterate over the set        for(let itr of set){            res += itr;        }         // Return Answer        return res;    }     // Driver Codevar arr = [ "your", "you",                            "or", "yo" ];document.write(minSubstr(arr)); // This code is contributed by 29AjayKumar</script>
  
ruyo
 
Time Complexity: O(N*M), where M is the average length of strings in the given arrayAuxiliary Space: O(1)
 
lokeshpotta20
29AjayKumar
Algo-Geek 2021
cpp-set
frequency-counting
Algo Geek
Hash
Mathematical
Searching
Strings
Searching
Hash
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Number of ways to divide a N elements equally into group of at least 2
Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X
Sort strings on the basis of their numeric part
Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index
Check if the given string is valid English word or not
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum