Given a string str, the task is to find the maximum count of common non-repeating characters that can be obtained by partitioning the given string into two non-empty substrings.
Examples:
Input : str = “aabbca”
Output: 2
Explanation:
Partition the string into two substrings { { str[0], … str[2] }, { str[3], …, str[5] } }
The common non-repeating characters present in both the substrings are { ‘a’, ‘b’}
Therefore, the required output is 2.Input: str = “aaaaaaaaaa”
Output: 1
Naive Approach: The simplest approach to solve this problem is to iterate over the characters of the string and partition the string into two non-empty substrings at every possible indices and count the number of common-repeating characters from the two substrings. Print the maximum count obtained.
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 count maximum common non-repeating// characters that can be obtained by partitioning// the string into two non-empty substringsint countCommonChar(int ind, string& S){ // Stores count of non-repeating characters // present in both the substrings int cnt = 0; // Stores distinct characters // in left substring set<char> ls; // Stores distinct characters // in right substring set<char> rs; // Traverse left substring for (int i = 0; i < ind; ++i) { // Insert S[i] into ls ls.insert(S[i]); } // Traverse right substring for (int i = ind; i < S.length(); ++i) { // Insert S[i] into rs rs.insert(S[i]); } // Traverse distinct characters // of left substring for (auto v : ls) { // If current character is // present in right substring if (rs.count(v)) { // Update cnt ++cnt; } } // Return count return cnt;}// Function to partition the string into// two non-empty substrings in all possible waysvoid partitionStringWithMaxCom(string& S){ // Stores maximum common distinct characters // present in both the substring partitions int ans = 0; // Traverse the string for (int i = 1; i < S.length(); ++i) { // Update ans ans = max(ans, countCommonChar(i, S)); } // Print count of maximum common // non-repeating characters cout << ans << "\n";}// Driver Codeint main(){ string str = "aabbca"; partitionStringWithMaxCom(str); return 0;} |
Java
// Java program to implement// the above approachimport java.util.*;class GFG{// Function to count maximum common non-repeating// characters that can be obtained by partitioning// the String into two non-empty subStringsstatic int countCommonChar(int ind, String S){ // Stores count of non-repeating characters // present in both the subStrings int cnt = 0; // Stores distinct characters // in left subString HashSet<Character> ls = new HashSet<Character>(); // Stores distinct characters // in right subString HashSet<Character> rs = new HashSet<Character>(); // Traverse left subString for (int i = 0; i < ind; ++i) { // Insert S[i] into ls ls.add(S.charAt(i)); } // Traverse right subString for (int i = ind; i < S.length(); ++i) { // Insert S[i] into rs rs.add(S.charAt(i)); } // Traverse distinct characters // of left subString for (char v : ls) { // If current character is // present in right subString if (rs.contains(v)) { // Update cnt ++cnt; } } // Return count return cnt;}// Function to partition the String into// two non-empty subStrings in all possible waysstatic void partitionStringWithMaxCom(String S){ // Stores maximum common distinct characters // present in both the subString partitions int ans = 0; // Traverse the String for (int i = 1; i < S.length(); ++i) { // Update ans ans = Math.max(ans, countCommonChar(i, S)); } // Print count of maximum common // non-repeating characters System.out.print(ans+ "\n");}// Driver Codepublic static void main(String[] args){ String str = "aabbca"; partitionStringWithMaxCom(str);}}// This code is contributed by 29AjayKumar |
Python3
# Python3 program to implement# the above approach# Function to count maximum common # non-repeating characters that can # be obtained by partitioning the # string into two non-empty substringsdef countCommonChar(ind, S): # Stores count of non-repeating # characters present in both the # substrings cnt = 0 # Stores distinct characters # in left substring ls = set() # Stores distinct characters # in right substring rs = set() # Traverse left substring for i in range(ind): # Insert S[i] into ls ls.add(S[i]) # Traverse right substring for i in range(ind, len(S)): # Insert S[i] into rs rs.add(S[i]) # Traverse distinct characters # of left substring for v in ls: # If current character is # present in right substring if v in rs: # Update cnt cnt += 1 # Return count return cnt# Function to partition the string # into two non-empty substrings in # all possible waysdef partitionStringWithMaxCom(S): # Stores maximum common distinct # characters present in both the # substring partitions ans = 0 # Traverse the string for i in range(1, len(S)): # Update ans ans = max(ans, countCommonChar(i, S)) # Print count of maximum common # non-repeating characters print(ans)# Driver Codeif __name__ == "__main__": string = "aabbca" partitionStringWithMaxCom(string)# This code is contributed by AnkThon |
2
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: To optimize the above approach, the idea is to use Hashing and Ordered Set to store the distinct characters of the string in sorted order. Follow the steps below to solve the problem:
- Initialize a variable, say res, to store the maximum count of common distinct characters present in both the substrings by partitioning the string into two substrings.
- Initialize a Map, say mp, to store the frequency of each distinct character of the string.
- Initialize an Ordered Set, say Q, to store the distinct characters of the string in sorted order.
- Iterate over characters of the string and for every ith character, decrement the frequency of str[i] and check if the frequency of mp[str[i]] is equal to 0 or not. If found to be false, then remove str[i] from the Ordered Set.
- Otherwise, insert str[i] in the ordered set and update res = max(res, X), where X is the count of elements in the ordered set.
- Finally, print the value of res.
Below is the implementation of the above approach:
C++
// C++ program to implement// the above approach#include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace std;using namespace __gnu_cxx;using namespace __gnu_pbds;template <typename T>using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;// Function to count maximum common non-repeating// characters that can be obtained by partitioning// the string into two non-empty substringsint countMaxCommonChar(string& S){ // Stores distinct characters // of S in sorted order ordered_set<char> Q; // Stores maximum common distinct characters // present in both the partitions int res = 0; // Stores frequency of each // distinct character n the string S map<char, int> freq; // Traverse the string for (int i = 0; i < S.length(); i++) { // Update frequency of S[i] freq[S[i]]++; } // Traverse the string for (int i = 0; i < S.length(); i++) { // Decreasing frequency of S[i] freq[S[i]]--; // If the frequency of S[i] is 0 if (!freq[S[i]]) { // Remove S[i] from Q Q.erase(S[i]); } else { // Insert S[i] into Q Q.insert(S[i]); } // Stores count of distinct // characters in Q int curr = Q.size(); // Update res res = max(res, curr); } cout << res << "\n";}// Driver Codeint main(){ string str = "aabbca"; // Function call countMaxCommonChar(str); return 0;} |
2
Time Complexity: O(N * log(N))
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
Recommended Posts:
- Number of ways to partition a string into two balanced subsequences
- Partition into two subarrays of lengths k and (N - k) such that the difference of sums is maximum
- Partition a set into two non-empty subsets such that the difference of subset sums is maximum
- Partition the string in two parts such that both parts have at least k different characters
- Partition a number into two divisible parts
- Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring
- Partition an array of non-negative integers into two subsets such that average of both the subsets is equal
- Partition the array into two odd length groups with minimized absolute difference between their median
- Partition a set into two subsets such that difference between max of one and min of other is minimized
- Count ways to partition a string such that both parts have equal distinct characters
- Count of ungrouped characters after dividing a string into K groups of distinct characters
- Partition array into minimum number of equal length subsets consisting of a single distinct value
- Number of ways to insert two pairs of parentheses into a string of N characters
- Check if a string can be split into two strings with same number of K-frequent characters
- Permutation of a string with maximum number of characters greater than its adjacent characters
- Partition the array into three equal sum segments
- Maximum String Partition
- Pair of strings having longest common prefix of maximum length in given array
- Interleaving of two given strings with no common characters
- Count common characters in two strings
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

