Find minimum number of Substrings with unique characters
Last Updated : 19 Apr, 2023
Given string 's', the task is to divide a given string s into multiple substrings, with each substring containing only unique characters. This means that no character should be repeated within a single substring. The goal is to find the minimum number of such substrings required to satisfy this condition.
Examples:
Input: s = "abacaba"
Output: 4
Explanation: Two possible partitions are ("a", "ba", "cab", "a") and ("ab", "a", "ca", "ba"). It can be shown that 4 is the minimum number of substrings needed.
Input: s = "ssssss"
Output: 6
Explanation: The only valid partition is ("s", "s", "s", "s", "s", "s").
Naive Approach: The basic way to solve the problem follows the below idea:
- We initialize an empty set and iterate through the given string. For each character encountered, we check if it is already present in the set.
- If it is, this means that we need to start a new substring since the current substring has a repeated character. We increase our answer variable and clear the set to start a new substring. We then add the current character to the set.
- After iterating through the entire string, the value of the answer variable gives us the minimum number of substrings required to partition the given string such that each substring has unique characters.
Below is the implementation for the above approach:
C++ // C++ program to Finding minimum number // of Substrings with unique Characters #include <bits/stdc++.h> using namespace std; // Function to Find Minimum Number of // Substrings with Unique Characters int partitionString(string s) { // Create an unordered set to // store unique characters unordered_set<char> st; // Initialize the answer // variable to 1 int ans = 1; // Iterate through the given string for (int i = 0; i < s.size(); i++) { // Check if the current character // is already present in the set if (st.find(s[i]) != st.end()) { // If it is, increment the // answer variable and clear // the set to start a // new substring ans++; st.clear(); } // Add the current character // to the set st.insert(s[i]); } // Return the answer variable, which // gives the minimum number // of substrings required return ans; } // Drivers code int main() { string S = "abacaba"; // Function Call cout << "Minimum Number of Substrings with Unique " "Characters: " << partitionString(S); return 0; }
Java // Java program to Finding Minimum Number of Substrings with // Unique Characters import java.util.*; // Function to Find Minimum Number of Substrings with Unique // Characters class GFG { static int partitionString(String s) { // Create a HashSet to store unique characters Set<Character> set = new HashSet<>(); // Initialize the answer variable to 1 int ans = 1; // Iterate through the given string for (int i = 0; i < s.length(); i++) { // Check if the current character is already // present in the set if (set.contains(s.charAt(i))) { // If it is, increment the answer variable // and clear the set to start a new // substring ans++; set.clear(); } // Add the current character to the set set.add(s.charAt(i)); } // Return the answer variable, which gives the // minimum number of substrings required return ans; } public static void main(String[] args) { String S = "abacaba"; System.out.print(partitionString(S)); } } // This code is contributed by Ravi Singh
Python3 # Function to Find Minimum Number of # Substrings with Unique Characters def partitionString(s): # Create an unordered set to # store unique characters st = set() # Initialize the answer # variable to 1 ans = 1 # Iterate through the given string for i in range(len(s)): # Check if the current character # is already present in the set if s[i] in st: # If it is, increment the # answer variable and clear # the set to start a # new substring ans += 1 st.clear() # Add the current character # to the set st.add(s[i]) # Return the answer variable, which # gives the minimum number # of substrings required return ans # Drivers code S = "abacaba" # Function Call print("Minimum Number of Substrings with Unique Characters:", partitionString(S))
C# // C# program to Finding Minimum Number of Substrings with // Unique Characters using System; using System.Collections.Generic; public class GFG { static int partitionString(string s) { // Create a HashSet to store unique characters HashSet<char> set = new HashSet<char>(); // Initialize the answer variable to 1 int ans = 1; // Iterate through the given string for (int i = 0; i < s.Length; i++) { // Check if the current character is already // present in the set if (set.Contains(s[i])) { // If it is, increment the answer variable // and clear the set to start a new // substring ans++; set.Clear(); } // Add the current character to the set set.Add(s[i]); } // Return the answer variable, which gives the // minimum number of substrings required return ans; } static public void Main() { // Code String S = "abacaba"; Console.Write("Minimum Number of Substrings with Unique Characters: " + partitionString(S)); } } // THis code is contributed by karthik
JavaScript // JavaScript program to Finding minimum number // of Substrings with unique Characters // Function to Find Minimum Number of Substrings with Unique // Characters function partitionString(s) { // Create a set to store unique characters let st = new Set(); // Initialize the answer // variable to 1 let ans = 1; // Iterate through the given string for (let i = 0; i < s.length; i++) { // Check if the current character // is already present in the set if (st.has(s[i])) { // If it is, increment the // answer variable and clear // the set to start a // new substring ans++; st.clear(); } // Add the current character // to the set st.add(s[i]); } // Return the answer variable, which // gives the minimum number // of substrings required return ans; } // Driver code let S = "abacaba"; // Function Call console.log( "Minimum Number of Substrings with Unique Characters: " + partitionString(S));
OutputMinimum Number of Substrings with Unique Characters: 4
Time Complexity: O(n) where n is the length of the input string.
Auxiliary Space: O(n) in the worst case This is because we store each character of the input string in the hash set, and in the worst case, all characters of the string are unique.
Efficient Approach: To solve the problem using a Greedy approach follow the below idea:
To solve this problem, we need to keep track of the last occurrence of each character in the string s. Whenever we encounter a repeated character, we know that the current substring contains a character that is repeated, so we need to start a new substring. We can determine the start of the new substring by setting the value of start to the index of the repeated character. We also increased the value of ans to indicate that we have started a new substring.
Below are the steps for the above approach:
- Create an array list of size 26 to store the last index of each character (initially set to -1).
Initialize the starting index of the current substring to 0. - Initialize the answer variable ans to 1.
- Iterate through the given string s:
- Get the index of the current character in the array by subtracting 'a' from it.
- Check if the current character is already present in the current substring by comparing its last index with the starting index of the current substring.
- If it is, increment the answer variable ans and update the starting index of the new substring to the current index.
- Update the last index of the current character in the array with the current index.
- Return the answer variable ans, which gives the minimum number of substrings required.
Below is the implementation for the above approach:
C++ // C++ program to Finding Minimum // Number of Substrings with // Unique Characters #include <bits/stdc++.h> using namespace std; // Function to Find Minimum Number of // Substrings with Unique characters int partitionString(string s) { // Create an array to store the // last index of each character vector<int> last(26, -1); // Initialize the starting index // of the current substring to 0 int start = 0; // Initialize the answer variable to 1 int ans = 1; // Iterate through the given string for (int i = 0; i < s.length(); i++) { // Get the index of the current // character in the array int index = s[i] - 'a'; // Check if the current character // is already present in the // current substring if (last[index] >= start) { // If it is, increment the answer // variable and update the // starting index of the // new substring ans++; start = i; } // Update the last index // of the current character last[index] = i; } // Return the answer variable, which // gives the minimum number of // substrings required return ans; } // Drivers code int main() { string S = "abacaba"; // Function Call cout << "Minimum Number of Substrings with Unique " "Characters: " << partitionString(S); return 0; }
Java // Java program to Finding Minimum Number of Substrings with // Unique Characters import java.util.*; // Function to Find Minimum Number of Substrings with Unique // Characters class GFG { static int partitionString(String s) { // Create an array to store the last index of each // character int[] last = new int[26]; Arrays.fill(last, -1); // Initialize the starting index of the current // substring to 0 int start = 0; // Initialize the answer variable to 1 int ans = 1; // Iterate through the given string for (int i = 0; i < s.length(); i++) { // Get the index of the current character in the // array int index = s.charAt(i) - 'a'; // Check if the current character is already // present in the current substring if (last[index] >= start) { // If it is, increment the answer variable // and update the starting index of the new // substring ans++; start = i; } // Update the last index of the current // character last[index] = i; } // Return the answer variable, which gives the // minimum number of substrings required return ans; } public static void main(String[] args) { String S = "ssssss"; System.out.print(partitionString(S)); } } // This code is contributed by Ravi Singh
Python3 # Function to Find Minimum Number of # Substrings with Unique characters def partitionString(s): # Create an array to store the # last index of each character last = [-1] * 26 # Initialize the starting index # of the current substring to 0 start = 0 # Initialize the answer variable to 1 ans = 1 # Iterate through the given string for i in range(len(s)): # Get the index of the current # character in the array index = ord(s[i]) - ord('a') # Check if the current character # is already present in the # current substring if last[index] >= start: # If it is, increment the answer # variable and update the # starting index of the # new substring ans += 1 start = i # Update the last index # of the current character last[index] = i # Return the answer variable, which # gives the minimum number of # substrings required return ans # Drivers code if __name__ == '__main__': S = "abacaba" # Function Call print("Minimum Number of Substrings with Unique Characters: ", partitionString(S))
C# using System; using System.Collections.Generic; public class Program { // Function to find minimum number of substrings with unique characters public static int PartitionString(string s) { // Create a dictionary to store the last index of each character Dictionary<char, int> last = new Dictionary<char, int>(); // Initialize the starting index of the current substring to 0 int start = 0; // Initialize the answer variable to 1 int ans = 1; // Iterate through the given string for (int i = 0; i < s.Length; i++) { char c = s[i]; // Check if the current character is // already present in the current substring if (last.ContainsKey(c) && last[c] >= start) { // If it is, increment the answer variable and // update the starting index of the new substring ans++; start = i; } // Update the last index of the current character last[c] = i; } // Return the answer variable, which gives // the minimum number of substrings required return ans; } // Driver's code public static void Main() { string S = "abacaba"; // Function call Console.WriteLine("Minimum Number of Substrings with Unique Characters: " + PartitionString(S)); } } // This code is contributed by Prajwal Kandekar
JavaScript // JavaScript program to Finding Minimum // Number of Substrings with // Unique Characters function partitionString(s) { // Create an array to store the // last index of each character const last = new Array(26).fill(-1); // Initialize the starting index // of the current substring to 0 let start = 0; // Initialize the answer variable to 1 let ans = 1; // Iterate through the given string for (let i = 0; i < s.length; i++) { // Get the index of the current // character in the array const index = s.charCodeAt(i) - 97; // Check if the current character // is already present in the // current substring if (last[index] >= start) { // If it is, increment the answer // variable and update the // starting index of the // new substring ans++; start = i; } // Update the last index // of the current character last[index] = i; } // Return the answer variable, which // gives the minimum number of // substrings required return ans; } // Example usage const S = "abacaba"; console.log(`Minimum Number of Substrings with Unique Characters: ${partitionString(S)}`);
OutputMinimum Number of Substrings with Unique Characters: 4
Time Complexity: O(n) where n is the length of the input string.
Auxiliary Space: O(1)
Similar Reads
Longest substring with k unique characters
Given a string you need to print longest possible substring that has exactly k unique characters. If there is more than one substring of longest possible length, then print any one of them. Note:- Source(Google Interview Question). Examples: Input: Str = "aabbcc", k = 1Output: 2Explanation: Max subs
13 min read
Count the number of unique characters in a given String
Given a string, str consisting of lowercase English alphabets, the task is to find the number of unique characters present in the string. Examples: Input: str = âgeeksforgeeksâOutput: 7Explanation: The given string âgeeksforgeeksâ contains 7 unique characters {âgâ, âeâ, âkâ, âsâ, âfâ, âoâ, ârâ}. Inp
14 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
Find the number of Substrings with even number of K
Given a string str of length N and an integer K, the task is to count the number of substrings with even numbers of K. It means the count of 'K' in each substring will be even and must not be zero. Examples: Input: N = 4, str = "2131", K = 1Output: 2 Explanation: There are two substrings "2131" and
8 min read
Count the number of Unique Characters in a String in Python
We are given a string, and our task is to find the number of unique characters in it. For example, if the string is "hello world", the unique characters are {h, e, l, o, w, r, d}, so the output should be 8. Using setSet in Python is an unordered collection of unique elements automatically removing d
2 min read
Number of substrings with each character occurring even times
Given a string S consisting of N lowercase alphabets, the task is to count the number of substrings whose frequency of each character is even. Examples: Input: S = "abbaa"Output: 4Explanation:The substrings having frequency of each character is even are {"abba", "aa", "bb", "bbaa"}.Therefore, the co
14 min read
Number of substrings with count of each character as k
Given a string and an integer k, find the number of substrings in which all the different characters occur exactly k times. Examples: Input : s = "aabbcc" k = 2 Output : 6 The substrings are aa, bb, cc, aabb, bbcc and aabbcc. Input : s = "aabccc" k = 2 Output : 3 There are three substrings aa, cc an
15 min read
Count the minimum number of groups formed in a string
Given a string 'S' which comprises two or more uppercase English letters. The task is to count the minimum number of groups required to completely cover the string by replacing consecutive characters with the same single character. Examples: Input : S = "TTWWW"Output : 2Explanation : There are 2 gro
7 min read
Count substrings with k distinct characters
Given a string consisting of lowercase characters and an integer k, the task is to count all possible substrings (not necessarily distinct) that have exactly k distinct characters. Examples: Input: s = "abc", k = 2Output: 2Explanation: Possible substrings are {"ab", "bc"} Input: s = "aba", k = 2Outp
10 min read
Number of substrings with equal character frequencies and fixed distance
Given a string S and an integer K, the task is to count the number of substrings which have each character exactly K times and maximum distance between two same characters <= K. Examples: Input: S= " de", K = 2Output: 3Explanation: "abab", "ababcc" and "cc" are substrings having each character ex
10 min read