Remove characters from given string whose frequencies are a Prime Number

Given string str of length N, the task is to remove all the characters from the string whose frequencies are prime.

Examples:

Input: str = “geeksforgeeks”
Output: eeforee
Explanation:
The frequencies of characters is: { g=2, e=4, k=2,  s=2, f=1, o=1, r=1}
So, g, k and s are the characters with prime frequencies so, they are removed from the string.
The resultant string is “eeforee”

Input: str = “abcdef”
Output: abcdef 
Explanation:
Since all the characters are unique with frequency as 1, so no character is removed.

Naive Approach: The simplest approach to solve this problem is to find the frequencies of every distinct character present in the string and for each character, check if its frequency is Prime or not. If the frequency is found to be prime, skip that character. Otherwise, append it to the new string formed. 



Time Complexity: O( N 3/2)
Auxiliary Space: O(N)

Efficient Approach: The above approach can be optimized by using the Sieve of Eratosthenes to precompute Prime Numbers. Follow the steps below to solve the problem:

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to perform the seive of
// eratosthenes algorithm
void SieveOfEratosthenes(bool* prime, int n)
{
    // Initialize all entries in
    // prime[] as true
    for (int i = 0; i <= n; i++) {
        prime[i] = true;
    }
 
    // Initialize 0 and 1 as non prime
    prime[0] = prime[1] = false;
 
    // Traversing the prime array
    for (int i = 2; i * i <= n; i++) {
 
        // If i is prime
        if (prime[i] == true) {
 
            // All multiples of i must
            // be marked false as they
            // are non prime
            for (int j = 2; i * j <= n; j++) {
                prime[i * j] = false;
            }
        }
    }
}
 
// Function to remove characters which
// have prime frequency in the string
void removePrimeFrequecies(string s)
{
    // Length of the string
    int n = s.length();
 
    // Create a boolean array prime
    bool prime[n + 1];
 
    // Sieve of Eratosthenes
    SieveOfEratosthenes(prime, n);
 
    // Stores the frequency of character
    unordered_map<char, int> m;
 
    // Storing the frequecies
    for (int i = 0; i < s.length(); i++) {
        m[s[i]]++;
    }
 
    // New string that will be formed
    string new_string = "";
 
    // Removing the characters which
    // have prime frequencies
    for (int i = 0; i < s.length(); i++) {
 
        // If the character has
        // prime frequency then skip
        if (prime[m[s[i]]])
            continue;
 
        // Else concatenate the
        // character to the new string
        new_string += s[i];
    }
 
    // Print the modified string
    cout << new_string;
}
 
// Driver Code
int main()
{
    string str = "geeksforgeeks";
 
    // Function Call
    removePrimeFrequecies(str);
 
    return 0;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to perform the seive of
// eratosthenes algorithm
static void SieveOfEratosthenes(boolean[] prime,
                                int n)
{
     
    // Initialize all entries in
    // prime[] as true
    for(int i = 0; i <= n; i++)
    {
        prime[i] = true;
    }
     
    // Initialize 0 and 1 as non prime
    prime[0] = prime[1] = false;
     
    // Traversing the prime array
    for(int i = 2; i * i <= n; i++)
    {
         
        // If i is prime
        if (prime[i] == true)
        {
             
            // All multiples of i must
            // be marked false as they
            // are non prime
            for(int j = 2; i * j <= n; j++)
            {
                prime[i * j] = false;
            }
        }
    }
}
 
// Function to remove characters which
// have prime frequency in the String
static void removePrimeFrequecies(char[] s)
{
     
    // Length of the String
    int n = s.length;
     
    // Create a boolean array prime
    boolean []prime = new boolean[n + 1];
     
    // Sieve of Eratosthenes
    SieveOfEratosthenes(prime, n);
 
    // Stores the frequency of character
    HashMap<Character, Integer> m = new HashMap<>();
     
    // Storing the frequecies
    for(int i = 0; i < s.length; i++)
    {
        if (m.containsKey(s[i]))
        {
            m.put(s[i], m.get(s[i]) + 1);
        }
        else
        {
            m.put(s[i], 1);
        }
    }
     
    // New String that will be formed
    String new_String = "";
     
    // Removing the characters which
    // have prime frequencies
    for(int i = 0; i < s.length; i++)
    {
         
        // If the character has
        // prime frequency then skip
        if (prime[m.get(s[i])])
            continue;
             
        // Else concatenate the
        // character to the new String
        new_String += s[i];
    }
     
    // Print the modified String
    System.out.print(new_String);
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "geeksforgeeks";
     
    // Function Call
    removePrimeFrequecies(str.toCharArray());
}
}
 
// This code is contributed by aashish1995
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to perform the seive of
// eratosthenes algorithm
static void SieveOfEratosthenes(bool[] prime,
                                int n)
{
     
    // Initialize all entries in
    // prime[] as true
    for(int i = 0; i <= n; i++)
    {
        prime[i] = true;
    }
     
    // Initialize 0 and 1 as non prime
    prime[0] = prime[1] = false;
     
    // Traversing the prime array
    for(int i = 2; i * i <= n; i++)
    {
         
        // If i is prime
        if (prime[i] == true)
        {
             
            // All multiples of i must
            // be marked false as they
            // are non prime
            for(int j = 2; i * j <= n; j++)
            {
                prime[i * j] = false;
            }
        }
    }
}
 
// Function to remove characters which
// have prime frequency in the String
static void removePrimeFrequecies(char[] s)
{
     
    // Length of the String
    int n = s.Length;
     
    // Create a bool array prime
    bool []prime = new bool[n + 1];
     
    // Sieve of Eratosthenes
    SieveOfEratosthenes(prime, n);
 
    // Stores the frequency of character
    Dictionary<char,
               int> m = new Dictionary<char,
                                       int>();
     
    // Storing the frequecies
    for(int i = 0; i < s.Length; i++)
    {
        if (m.ContainsKey(s[i]))
        {
            m[s[i]]++;
        }
        else
        {
            m.Add(s[i], 1);
        }
    }
     
    // New String that will be formed
    String new_String = "";
     
    // Removing the characters which
    // have prime frequencies
    for(int i = 0; i < s.Length; i++)
    {
         
        // If the character has
        // prime frequency then skip
        if (prime[m[s[i]]])
            continue;
             
        // Else concatenate the
        // character to the new String
        new_String += s[i];
    }
     
    // Print the modified String
    Console.Write(new_String);
}
 
// Driver Code
public static void Main(String[] args)
{
    String str = "geeksforgeeks";
     
    // Function Call
    removePrimeFrequecies(str.ToCharArray());
}
}
 
// This code is contributed by aashish1995
chevron_right

Output: 
eeforee

 

Time Complexity: O(N*log (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.




Article Tags :