Operations required to make the string empty

28 Jun, 2022
Given a string str, the task is to make the string empty with the given operation. In a single operation, you can pick some characters of the string (each of the picked characters should have the same frequency) and remove them from the string. Print the total operations required to make the string empty.Examples:  
Input: str = “aabbccc” Output: 2 In one operation, characters ‘a’ and ‘b’ can be removed since both have the same frequency. Second operation can remove character ‘c’ having frequency 3. Total 2 operations are required.Input: str = “geeksforgeeks” Output: 3  
 
Approach: Find unique frequencies of the characters of the string. Total count of unique frequencies will be the number of operations required to make the string empty. For str = “aaabbbcccc”, unique frequencies are 3 and 4. Total count of unique frequencies is 2. HashMap can be used to store the characters and their frequencies then HashSet can be used to find the count of unique frequencies which is the number of operations required.Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// CPP implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the count of operations requiredint totalOperations(string str, int len){    // HashMap to store characters and their frequencies    unordered_map<char, int> h;    for (int i = 0; i < len; i++)         // If already contains the character then        // increment its frequency by 1        h[str[i]]++;     // HashSet to store unique frequency    unordered_set<int> hs;     // Insert frequencies into HashSet    for (auto i : h)        hs.insert(i.second);     // Count of unique frequencies    return hs.size();} // Driver Codeint main(){    string str = "geeksforgeeks";    int len = str.length();     cout << totalOperations(str, len) << endl;    return 0;} // This code is contributed by// sanjeev2552
// Java implementation of the approachimport java.util.*;class GFG {     // Function to return the count of operations required    static int totalOperations(String str, int len)    {         // HashMap to store characters and their frequencies        HashMap<Character, Integer> h = new HashMap<Character, Integer>();        for (int i = 0; i < len; i++) {             // If already contains the character then            // increment its frequency by 1            if (h.containsKey(str.charAt(i)))                h.put(str.charAt(i), h.get(str.charAt(i)) + 1);             // Else add the character to the HashMap with frequency 1            else                h.put(str.charAt(i), 1);        }         // Set to iterate over HashMap        Set<Map.Entry<Character, Integer> > set = h.entrySet();         // HashSet to store unique frequency        HashSet<Integer> hs = new HashSet<Integer>();         // Insert frequencies into HashSet        for (Map.Entry<Character, Integer> me : set)            hs.add(me.getValue());         // Count of unique frequencies        return hs.size();    }     // Driver code    public static void main(String[] args)    {        String str = "geeksforgeeks";        int len = str.length();        System.out.println(totalOperations(str, len));    }}
# Python implementation of the approach # Function to return the count of operations requireddef totalOperations(st, length):         # Dictionary to store characters and their frequencies    d = {}    for i in range(length):                 # If already contains the character then        # increment its frequency by 1        if st[i] in d:            d[st[i]] += 1                 # Else add the character to the HashMap with frequency 1        else:            d[st[i]] = 1     # Set to Store unique frequency    valueSet = set()     # Insert frequencies into HashSet    for key in d.keys():        valueSet.add(d[key])         # Count of unique frequencies    return len(valueSet) # Driver Codest = "geeksforgeeks"l = len(st)print(totalOperations(st, l)) # This code is contributed by Vivekkumar Singh
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to return// the count of operations requiredstatic int totalOperations(String str, int len){     // HashMap to store characters    // and their frequencies    Dictionary<char,               int> h = new Dictionary<char,                                       int>();    for (int i = 0; i < len; i++)    {         // If already contains the character then        // increment its frequency by 1        if (h.ContainsKey(str[i]))            h[str[i]] = h[str[i]] + 1;         // Else add the character        // to the HashMap with frequency 1        else            h.Add(str[i], 1);    }     // Set to iterate over HashMap    // HashSet to store unique frequency    HashSet<int> hs = new HashSet<int>();     // Insert frequencies into HashSet    foreach(KeyValuePair<char, int> me in h)        hs.Add(me.Value);     // Count of unique frequencies    return hs.Count;} // Driver codepublic static void Main(String[] args){    String str = "geeksforgeeks";    int len = str.Length;    Console.WriteLine(totalOperations(str, len));}} // This code is contributed by Rajput-Ji
<script> // Javascript implementation of the approach // Function to return the count of operations requiredfunction totalOperations(str, len){    // HashMap to store characters and their frequencies    var h = new Map();    for (var i = 0; i < len; i++)         // If already contains the character then        // increment its frequency by 1        if(h.has(str[i]))            h.set(str[i], h.get(str[i])+1)        else            h.set(str[i], 1)     // HashSet to store unique frequency    var hs = new Set();     // Insert frequencies into HashSet    h.forEach((value, key) => {                 hs.add(value);    });     // Count of unique frequencies    return hs.size;} // Driver Codevar str = "geeksforgeeks";var len = str.length;document.write( totalOperations(str, len)); // This code is contributed by itsok.</script>
3
 
Time complexity: O(n)
Auxiliary Space: O(n)
Vivekkumar Singh
Rajput-Ji
sanjeev2552
itsok
krishnav4
HashSet
Thoughtworks
Competitive Programming
Java
Strings
Thoughtworks
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Bitwise Hacks for Competitive Programming
Container with Most Water
Most important type of Algorithms
Find two numbers from their sum and XOR
The Ultimate Beginner's Guide For DSA
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java