Friday, October 10, 2025
HomeData Modelling & AIRemove characters from string that appears strictly less than K times

Remove characters from string that appears strictly less than K times

Given a string of lowercase letters and a number K. The task is to reduce it by removing the characters which appear strictly less than K times in the string.

Examples:

Input : str = "neveropen", K = 2
Output : neveropenneveropen

Input : str = "neveropen", 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++




// 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 times
string 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 Code
int main()
{
    string str = "neveropen";
    int k = 2;
 
    cout << removeChars(str, k);
 
    return 0;
}


Java




// Java program to reduce the string by
// removing the characters which
// appears less than k times
class 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 = "neveropen";
        int k = 2;
 
        System.out.println(removeChars(str, k));
    }
}
 
// This code is contributed by 29AjayKumar


Python 3




# Python 3 program to reduce the string
# by removing the characters which
# appears less than k times
MAX_CHAR = 26
 
# Function to reduce the string by
# removing the characters which
# appears less than k times
def 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 Code
if __name__ == "__main__":
     
    str = "neveropen"
    k = 2
 
    print(removeChars(str, k))
 
# This code is contributed by ita_c


C#




// C# program to reduce the string by
// removing the characters which
// appears less than k times
using 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 = "neveropen";
        int k = 2;
 
        Console.WriteLine(removeChars(str, k));
    }
}
 
// This code is contributed by Rajput-Ji


Javascript




<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 times
function 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 Code
let str = "neveropen";
let k = 2;
 
document.write(removeChars(str, k));
 
// This code is contributed by rag2127
</script>


Output

neveropenneveropen

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Method #2:Using Built-in Python functions:

  • 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 appear less than k times.

Note: This method is applicable to all types of characters.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <unordered_map>
using namespace std;
 
string removeChars(string str, int k) {
    // Using an unordered_map to count frequencies
    unordered_map<char, int> freq;
    for (int i = 0; i < str.length(); i++) {
        char c = str[i];
        freq++;
    }
 
    // Create a new empty string
    string res = "";
 
    for (int i = 0; i < str.length(); i++) {
        // Append the characters which appear
        // more than or equal to k times
        if (freq[str[i]] >= k) {
            res += str[i];
        }
    }
 
    return res;
}
 
int main() {
    string str = "neveropen";
    int k = 2;
    cout << removeChars(str, k) << endl;
    return 0;
}


Java




import java.util.HashMap;
 
class Main {
    // Function to reduce the string by
    // removing the characters which
    // appear less than k times
    public static String removeChars(String str, int k)
    {
 
        // Using a HashMap to count frequencies
        HashMap<Character, Integer> freq
            = new HashMap<Character, Integer>();
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            freq.put(c, freq.getOrDefault(c, 0) + 1);
        }
 
        // Create a new empty string
        StringBuilder res = new StringBuilder();
 
        for (int i = 0; i < str.length(); i++) {
 
            // Append the characters which
            // appear more than or equal to k times
            if (freq.get(str.charAt(i)) >= k) {
                res.append(str.charAt(i));
            }
        }
 
        return res.toString();
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str = "neveropen";
        int k = 2;
        System.out.println(removeChars(str, k));
    }
}


Python3




# Python 3 program to reduce the string
# by removing the characters which
# appears less than k times
from collections import Counter
 
# Function to reduce the string by
# removing the characters which
# appears less than k times
def 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 Code
if __name__ == "__main__":
 
    str = "neveropen"
    k = 2
 
    print(removeChars(str, k))
 
# This code is contributed by vikkycirus


C#




using System;
using System.Collections.Generic;
 
class Program {
    static string RemoveChars(string str, int k)
    {
        // Using a Dictionary to count frequencies
        Dictionary<char, int> freq
            = new Dictionary<char, int>();
        for (int i = 0; i < str.Length; i++) {
            char c = str[i];
            if (freq.ContainsKey(c)) {
                freq++;
            }
            else {
                freq = 1;
            }
        }
 
        // Create a new empty string
        string res = "";
 
        for (int i = 0; i < str.Length; i++) {
            // Append the characters which appear
            // more than or equal to k times
            if (freq[str[i]] >= k) {
                res += str[i];
            }
        }
 
        return res;
    }
 
    static void Main(string[] args)
    {
        string str = "neveropen";
        int k = 2;
        Console.WriteLine(RemoveChars(str, k));
    }
}


Javascript




// Function to reduce the string by
// removing the characters which
// appears less than k times
function removeChars(str, k) {
   
    // Using an object to count frequencies
    let freq = {};
    for (let i = 0; i < str.length; i++) {
        if (freq[str[i]]) {
            freq[str[i]]++;
        } else {
            freq[str[i]] = 1;
        }
    }
     
    // Create a new empty string
    let res = "";
 
    for (let i = 0; i < str.length; i++) {
 
        // Append the characters which
        // appears more than equal to k times
        if (freq[str[i]] >= k) {
            res += str[i];
        }
    }
 
    return res;
}
 
// Driver Code
let str = "neveropen";
let k = 2;
 
console.log(removeChars(str, k));
 
// This code is contriibuted by codebraxnzt


Output

neveropenneveropen

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(1), no extra space is required, so it is a constant.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Dominic
32348 POSTS0 COMMENTS
Milvus
87 POSTS0 COMMENTS
Nango Kala
6715 POSTS0 COMMENTS
Nicole Veronica
11878 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11941 POSTS0 COMMENTS
Shaida Kate Naidoo
6837 POSTS0 COMMENTS
Ted Musemwa
7097 POSTS0 COMMENTS
Thapelo Manthata
6792 POSTS0 COMMENTS
Umr Jansen
6791 POSTS0 COMMENTS