Remove characters from string that appears strictly less than K times - GeeksforGeeks

21 Jul, 2021
Given a string of lowercase letters and a number K. The task is to reduce it by removing the characters which appears strictly less than K times in the string.Examples: 
Input : str = "geeksforgeeks", K = 2
Output : geeksgeeks

Input : str = "geeksforgeeks", K = 3
Output : eeee
Approach :  
Create a hash table of 26 indexes, where 0th index representing ‘a’ and 1th index represent ‘b’ and so on to store the frequency of each of the characters in the input string. Initialize this hash table to zero.
Iterate through the string and increment the frequency of each character in the hash table. That is, hash[str[i]-‘a’]++.
Now create a new empty string and once again traverse through the input string and append-only those characters in the new string whose frequency in the hash table is more than or equal to k and skip those which appear less than k times.
Below is the implementation of the above approach: 
C++
Java
Python 3
C#
Javascript
// C++ program to reduce the string by// removing the characters which// appears less than k times #include <bits/stdc++.h>using namespace std; const int MAX_CHAR = 26; // Function to reduce the string by// removing the characters which// appears less than k timesstring removeChars(string str, int k){    // Hash table initialised to 0    int hash[MAX_CHAR] = { 0 };     // Increment the frequency of the character    int n = str.length();    for (int i = 0; i < n; ++i)        hash[str[i] - 'a']++;     // create a new empty string    string res = "";    for (int i = 0; i < n; ++i) {         // Append the characters which        // appears more than equal to k times        if (hash[str[i] - 'a'] >= k) {            res += str[i];        }    }     return res;} // Driver Codeint main(){    string str = "geeksforgeeks";    int k = 2;     cout << removeChars(str, k);     return 0;}
// Java program to reduce the string by// removing the characters which// appears less than k timesclass GFG {     final static int MAX_CHAR = 26; // Function to reduce the string by// removing the characters which// appears less than k times    static String removeChars(String str, int k) {        // Hash table initialised to 0        int hash[] = new int[MAX_CHAR];         // Increment the frequency of the character        int n = str.length();        for (int i = 0; i < n; ++i) {            hash[str.charAt(i) - 'a']++;        }         // create a new empty string        String res = "";        for (int i = 0; i < n; ++i) {             // Append the characters which            // appears more than equal to k times            if (hash[str.charAt(i) - 'a'] >= k) {                res += str.charAt(i);            }        }         return res;    } // Driver Code    static public void main(String[] args) {        String str = "geeksforgeeks";        int k = 2;         System.out.println(removeChars(str, k));    }} // This code is contributed by 29AjayKumar
# Python 3 program to reduce the string# by removing the characters which# appears less than k timesMAX_CHAR = 26 # Function to reduce the string by# removing the characters which# appears less than k timesdef removeChars(str, k):     # Hash table initialised to 0    hash = [0] * (MAX_CHAR)     # Increment the frequency of    # the character    n = len(str)    for i in range(n):        hash[ord(str[i]) - ord('a')] += 1     # create a new empty string    res = ""    for i in range(n):         # Append the characters which        # appears more than equal to k times        if (hash[ord(str[i]) - ord('a')] >= k) :            res += str[i]     return res # Driver Codeif __name__ == "__main__":         str = "geeksforgeeks"    k = 2     print(removeChars(str, k)) # This code is contributed by ita_c
// C# program to reduce the string by// removing the characters which// appears less than k timesusing System;class GFG{     readonly static int MAX_CHAR = 26;     // Function to reduce the string by    // removing the characters which    // appears less than k times    static String removeChars(String str, int k)     {        // Hash table initialised to 0        int []hash = new int[MAX_CHAR];         // Increment the frequency of the character        int n = str.Length;        for (int i = 0; i < n; ++i)        {            hash[str[i] - 'a']++;        }         // create a new empty string        String res = "";        for (int i = 0; i < n; ++i)        {             // Append the characters which            // appears more than equal to k times            if (hash[str[i] - 'a'] >= k)            {                res += str[i];            }        }         return res;    }     // Driver Code    static public void Main()    {        String str = "geeksforgeeks";        int k = 2;         Console.WriteLine(removeChars(str, k));    }} // This code is contributed by Rajput-Ji
<script>// Javascript program to reduce the string by// removing the characters which// appears less than k times let MAX_CHAR = 26; // Function to reduce the string by// removing the characters which// appears less than k timesfunction removeChars(str,k){    // Hash table initialised to 0        let hash = new Array(MAX_CHAR);         for(let i=0;i<MAX_CHAR;i++)            hash[i]=0;        // Increment the frequency of the character        let n = str.length;        for (let i = 0; i < n; ++i) {            hash[str[i].charCodeAt(0) - 'a'.charCodeAt(0)]++;        }          // create a new empty string        let res = "";        for (let i = 0; i < n; ++i) {              // Append the characters which            // appears more than equal to k times            if (hash[str[i].charCodeAt(0) - 'a'.charCodeAt(0)] >= k) {                res += str[i];            }        }          return res;} // Driver Codelet str = "geeksforgeeks";let k = 2; document.write(removeChars(str, k)); // This code is contributed by rag2127</script>
geeksgeeks
 
Time Complexity: O(N), where N is the length of the given string.
We will scan the string and count the occurrence of all characters  using built in Counter() function .
Now create a new empty string and once again traverse through the input string and append only those characters in the new string whose frequency dictionary value is more than or equal to k and skip those which appears less than k times.
Note: This method is applicable for all types of characters.
Below is the implementation of the above approach:
Python3
# Python 3 program to reduce the string# by removing the characters which# appears less than k timesfrom collections import Counter # Function to reduce the string by# removing the characters which# appears less than k timesdef removeChars(str, k):       # Using Counter function to    # count frequencies    freq = Counter(str)         # Create a new empty string    res = ""     for i in range(len(str)):         # Append the characters which        # appears more than equal to k times        if (freq[str[i]] >= k):            res += str[i]     return res  # Driver Codeif __name__ == "__main__":     str = "geeksforgeeks"    k = 2     print(removeChars(str, k)) # This code is contributed by vikkycirus
Output:
geeksgeeks
ukasp
29AjayKumar
Rajput-Ji
vikkycirus
rag2127
frequency-counting
Technical Scripter 2018
Strings
Technical Scripter
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews