Smallest string containing all unique characters from given array of strings
Last Updated :
17 Feb, 2023
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: ruyo
Explanation: The string "ruyo" is the smallest string which contains all the characters that are used across all the strings of the given array.
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++
// 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 Code
int main()
{
vector<string> arr = {"your", "you",
"or", "yo"};
cout << (minSubstr(arr));
return 0;
}
// This code is contributed by Potta Lokesh
Java
import 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));
}
}
Python3
# Python code for the above approach
def 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
_set = set()
# Loop to iterate over all
# the characters in str
for i in range(len(str)):
_set.add(str[i])
# Stores the required answer
res = ""
# Loop to iterate over the set
for itr in _set:
res += itr
# Return Answer
return res
# Driver Code
arr = ["your", "you", "or", "yo"]
print(minSubstr(arr))
# This code is contributed by gfgking
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
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 i in set) {
res += i;
}
// Return Answer
return res;
}
// Driver Code
public static void Main()
{
string []arr
= { "your", "you", "or", "yo" };
Console.WriteLine(minSubstr(arr));
}
}
// This code is contributed by Samim Hossain Mondal.
JavaScript
<script>
// JavaScript code for the above approach
function minSubstr(s)
{
// Stores the concatenated string
// of all the given strings
let str = "";
// Loop to iterate through all
// the given strings
for (let i = 0; i < s.length; i++) {
str += s[i];
}
// Set to store the characters
let set = new Set();
// Loop to iterate over all
// the characters in str
for (let i = 0; i < str.length; i++) {
set.add(str[i]);
}
// Stores the required answer
let res = "";
// Loop to iterate over the set
for (let itr of set) {
res += itr;
}
// Return Answer
return res;
}
// Driver Code
let arr
= ["your", "you",
"or", "yo"];
document.write(minSubstr(arr));
// This code is contributed by Potta Lokesh
</script>
Time Complexity: O(N*M), where M is the average length of strings in the given array
Auxiliary Space: O(N) because extra space for string str is being used
Approach #2: This problem can also be solved by using the Map Data Structure. Map stores all the characters present in the string with their occurrence. After iterating on the map we will get the all unique characters.
C++
// 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];
}
// map to store the characters with frequency
unordered_map<char, int> mp;
// Loop to iterate over all
// the characters in str
for (int i = 0; i < str.length(); i++) {
mp[str[i]]++;
}
string res = "";
// Loop to iterate over the map
for (auto it : mp) {
res += it.first;
}
// Return Answer
return res;
}
// Driver Code
int main()
{
vector<string> arr = { "your", "you", "or", "yo" };
cout << (minSubstr(arr));
return 0;
}
// This code is contributed by Prasad Kandekar(prasad264)
Java
// Java code for the above approach
import java.util.*;
class GFG {
public static String minSubstr(List<String> s)
{
// Stores the concatenated string
// of all the given strings
String str = "";
// Loop to iterate through all
// the given strings
for (String x : s) {
str += x;
}
// map to store the characters with frequency
Map<Character, Integer> mp = new HashMap<>();
// Loop to iterate over all
// the characters in str
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (mp.containsKey(c)) {
mp.put(c, mp.get(c) + 1);
}
else {
mp.put(c, 1);
}
}
StringBuilder res = new StringBuilder();
// Loop to iterate over the map
for (Map.Entry<Character, Integer> entry :
mp.entrySet()) {
res.append(entry.getKey());
}
// Return Answer
return res.toString();
}
// Driver Code
public static void main(String[] args)
{
List<String> arr
= Arrays.asList("your", "you", "or", "yo");
System.out.println(minSubstr(arr));
}
}
// This code is contributed by Prasad Kandekar(prasad264)
Python3
# Python code for the above approach
def min_substr(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]
# dictionary to store the characters with frequency
mp = {}
# Loop to iterate over all
# the characters in str
for i in range(len(str)):
if str[i] in mp:
mp[str[i]] += 1
else:
mp[str[i]] = 1
res = ""
# Loop to iterate over the map
for key in mp:
res += key
# Return Answer
return res
# Driver Code
arr = ["your", "you", "or", "yo"]
print(min_substr(arr))
# This code is contributed by karthik
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
public class GFG {
static string MinSubstr(List<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.Count; i++) {
str += s[i];
}
// dictionary to store the characters with frequency
Dictionary<char, int> mp
= new Dictionary<char, int>();
// Loop to iterate over all
// the characters in str
for (int i = 0; i < str.Length; i++) {
if (mp.ContainsKey(str[i])) {
mp[str[i]]++;
}
else {
mp[str[i]] = 1;
}
}
string res = "";
// Loop to iterate over the map
foreach(var item in mp) { res += item.Key; }
// Return Answer
return res;
}
// Driver Code
static public void Main(string[] args)
{
List<string> arr = new List<string>() {
"your", "you", "or", "yo"
};
Console.WriteLine(MinSubstr(arr));
}
}
// This code is contributed by Prasad Kandekar(prasad264)
JavaScript
// JavaScript code for the above approach
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];
}
// map to store the characters with frequency
var mp = new Map();
// Loop to iterate over all
// the characters in str
for (var i = 0; i < str.length; i++) {
if (mp.has(str[i])) {
mp.set(str[i], mp.get(str[i]) + 1);
}
else {
mp.set(str[i], 1);
}
}
var res = "";
// Loop to iterate over the map
for (var [key, value] of mp) {
res += key;
}
// Return Answer
return res;
}
// Driver Code
var arr = ["your", "you", "or", "yo"];
console.log(minSubstr(arr));
// This code is contributed by Prasad Kandekar(prasad264)
Output:
ruoy
Complexity analysis:
Time Complexity: O(N*M), where M is the average length of strings in the given array
Auxiliary Space: O(N) because extra space for string str and unordered_map are being used
Similar Reads
Smallest window in a String containing all characters of other String
Given two strings s (length m) and p (length n), the task is to find the smallest substring in s that contains all characters of p, including duplicates. If no such substring exists, return "-1". If multiple substrings of the same length are found, return the one with the smallest starting index.Exa
15+ min read
Maximize length of the String by concatenating characters from an Array of Strings
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: 8Explanation: All possible combinations are {"", "abcd", "efgh", "abc
12 min read
Counting K-Length Strings with Fixed Character in a Unique String
Given a string S of length n containing distinct characters and a character C , the task is to count k-length strings that can be formed using characters from the string S, ensuring each string includes the specified character C, and no characters from the given string S are used more than once. Ret
9 min read
Smallest window that contains all characters of string itself
Given a string str, your task is to find the smallest window length that contains all the characters of the given string at least one time.Examples: Input: str = "aabcbcdbca"Output: 4Explanation: Sub-string -> "dbca"Input: str = "aaab"Output: 2Explanation: Sub-string -> "ab"Table of Content[Na
8 min read
Count of strings that does not contain any character of a given string
Given an array arr containing N strings and a string str, the task is to find the number of strings that do not contain any character of string str. Examples: Input: arr[] = {"abcd", "hijk", "xyz", "ayt"}, str="apple"Output: 2Explanation: "hijk" and "xyz" are the strings that do not contain any char
8 min read
Count substrings of same length differing by a single character from two given strings
Given two strings S and T of length N and M respectively, the task is to count the number of ways of obtaining same-length substring from both the strings such that they have a single different character. Examples: Input: S = "ab", T = "bb"Output: 3Explanation: The following are the pairs of substri
7 min read
Create a string with unique characters from the given N substrings
Given an array arr[] containing N substrings consisting of lowercase English letters, the task is to return the minimum length string that contains all given parts as a substring. All characters in this new answer string should be distinct. If there are multiple strings with the following property p
11 min read
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: ruyoExplanati
5 min read
Count strings from given array having all characters appearing in a given string
Given an array of strings arr[][] of size N and a string S, the task is to find the number of strings from the array having all its characters appearing in the string S. Examples: Input: arr[][] = {"ab", "aab", "abaaaa", "bbd"}, S = "ab"Output: 3Explanation: String "ab" have all the characters occur
6 min read
Count of all unique substrings with non-repeating characters
Given a string str consisting of lowercase characters, the task is to find the total number of unique substrings with non-repeating characters. Examples: Input: str = "abba" Output: 4 Explanation: There are 4 unique substrings. They are: "a", "ab", "b", "ba". Input: str = "acbacbacaa" Output: 10 App
6 min read