Number of Positions to partition the string such that atleast m characters with same frequency are present in each substring

Given a string str of lowercase English alphabets and an integer m. The task is to count how many positions are there in the string such that if you partition the string into two non-empty sub-strings, there are at least m characters with the same frequency in both the sub-strings.

The characters need to be present in the string str.

Examples:

Input: str = “aabbccaa”, m = 2
Output: 2
The string has length 8, so there are 7 positions available to perform the partition.
i.e. a|a|b|b|c|c|a|a
Only two partitions are possible which satisfy the given constraints.
aab|bccaa – On the left half of the separator, ‘a’ has frequency 2 and ‘b’ has frequency 1
which is same as that of the right half.
aabbc|caa – On the left half of the separator, ‘a’ has frequency 2 and ‘c’ has frequency 1
which is same as that of the right half.

Input: str = “aabbaa”, m = 2
Output: 1

Approach: For each partition position, calculate the frequencies of each of the characters of the string in both the partitions. Then calculate the number of characters having same frequency in both partitions. If the count of such characters is at least m then add 1 to the required count of partitions.

Below is the implementation of the above approach:

Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.*;
  
class GFG {
  
    // Function to return the number of ways
    // to partition the given so that the
    // given condition is satisfied
    static int countWays(String str, int m)
    {
  
        // Hashset to store unique characters
        // in the given string
        HashSet<Character> set = new HashSet<Character>();
        for (int i = 0; i < str.length(); i++)
            set.add(str.charAt(i));
  
        // To store the number of ways
        // to partition the string
        int result = 0;
  
        for (int i = 1; i < str.length(); i++) {
  
            // Hashmaps to store frequency of characters
            // of both the partitions
            HashMap<Character, Integer> first_map
                = new HashMap<Character, Integer>();
            HashMap<Character, Integer> second_map
                = new HashMap<Character, Integer>();
  
            // Iterate in the first partition
            for (int j = 0; j < i; j++) {
  
                // If character already exists in the hashmap
                // then increase it's frequency
                if (first_map.containsKey(str.charAt(j)))
                    first_map.put(str.charAt(j),
                                  (first_map.get(str.charAt(j)) + 1));
  
                // Else create an entry for it in the Hashmap
                else
                    first_map.put(str.charAt(j), 1);
            }
  
            // Iterate in the second partition
            for (int k = i; k < str.length(); k++) {
  
                // If character already exists in the hashmap
                // then increase it's frequency
                if (second_map.containsKey(str.charAt(k)))
                    second_map.put(str.charAt(k),
                                   (second_map.get(str.charAt(k)) + 1));
  
                // Else create an entry for it in the Hashmap
                else
                    second_map.put(str.charAt(k), 1);
            }
  
            // Iterator for HashSet
            Iterator itr = set.iterator();
  
            // To store the count of characters that have
            // equal frequencies in both the partitions
            int total_count = 0;
  
            while (itr.hasNext()) {
  
                // first_count and second_count keeps track
                // of the frequencies of each character
                int first_count = 0, second_count = 0;
                char ch = (char)itr.next();
  
                // Frequency of the character
                // in the first partition
                if (first_map.containsKey(ch))
                    first_count = first_map.get(ch);
  
                // Frequency of the character
                // in the second partition
                if (second_map.containsKey(ch))
                    second_count = second_map.get(ch);
  
                // Check if frequency is same in both the partitions
                if (first_count == second_count && first_count != 0)
                    total_count += 1;
            }
  
            // Check if the condition is satisfied
            // for the current partition
            if (total_count >= m)
                result += 1;
        }
  
        return result;
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str = "aabbccaa";
        int m = 2;
        System.out.println(countWays(str, m));
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 implementation of the approach 
from collections import defaultdict
  
# Function to return the number of ways 
# to partition the given so that the 
# given condition is satisfied 
def countWays(string, m):
  
    # Hashset to store unique 
    # characters in the given string 
    Set = set() 
    for i in range(0, len(string)): 
        Set.add(string[i]) 
  
    # To store the number of ways 
    # to partition the string 
    result = 0
  
    for i in range(1, len(string)): 
  
        # Hashmaps to store frequency of 
        # characters of both the partitions 
        first_map = defaultdict(lambda:0
        second_map = defaultdict(lambda:0
  
        # Iterate in the first partition 
        for j in range(0, i): 
  
            first_map[string[j]] += 1
          
        # Iterate in the second partition 
        for k in range(i, len(string)): 
  
            second_map[string[k]] += 1
          
        # To store the count of characters that have 
        # equal frequencies in both the partitions 
        total_count = 0
  
        for ch in Set
  
            # first_count and second_count keeps track 
            # of the frequencies of each character 
            first_count, second_count = 0, 0
  
            # Frequency of the character 
            # in the first partition 
            if ch in first_map: 
                first_count = first_map[ch] 
  
            # Frequency of the character 
            # in the second partition 
            if ch in second_map: 
                second_count = second_map[ch] 
  
            # Check if frequency is same in both the partitions 
            if first_count == second_count and first_count != 0
                total_count += 1
          
        # Check if the condition is satisfied 
        # for the current partition 
        if total_count >= m:
            result += 1
      
    return result 
  
# Driver code 
if __name__ == "__main__":
  
    string = "aabbccaa"
    m = 2
    print(countWays(string, m)) 
      
# This code is contributed by Rituraj Jain

chevron_right


Output:

2


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.