Find smallest string with whose characters all given Strings can be generated
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: ruyo
Explanation: 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.
Java
// 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)); }} |
ruyo
Time Complexity: O(N*M), where M is the average length of strings in the given array
Auxiliary Space: O(1)



