Open In App

Remove odd frequency characters from the string

Improve
Improve
Like Article
Like
Save
Share
Report

Given string str of size N, the task is to remove all the characters from the string that have odd frequencies.

Examples: 

Input: str = “geeksforgeeks” 
Output: geeksgeeks 
The characters f, o, r have odd frequencies 
So, they are removed from the string.

Input: str = “zzzxxweeerr” 
Output: xxrr 

Approach: 

  • Create a map and store the frequency of each character from the string to the same map.
  • Then, traverse the string and find out which characters have odd frequencies with the help of the map.
  • Ignore all those characters which have odd frequencies and store the rest in a new string.
  • Finally, display the new string.

Below is the implementation of the above approach: 

C++




// C++ program to remove the characters
// having odd frequencies in the string
#include <bits/stdc++.h>
using namespace std;
 
// Function to remove the characters which
// have odd frequencies in the string
string removeOddFrequencyCharacters(string s)
{
    // Create a map to store the
    // frequency of each character
    unordered_map<char, int> m;
    for (int i = 0; i < s.length(); i++) {
        m[s[i]]++;
    }
 
    // To store the new string
    string new_string = "";
 
    // Remove the characters which
    // have odd frequencies
    for (int i = 0; i < s.length(); i++) {
 
        // If the character has
        // odd frequency then skip
        if (m[s[i]] & 1)
            continue;
 
        // Else concatenate the
        // character to the new string
        new_string += s[i];
    }
 
    // Return the modified string
    return new_string;
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
 
    // Remove the characters which
    // have odd frequencies
    str = removeOddFrequencyCharacters(str);
    cout << str << "\n";
 
    return 0;
}


Java




// Java program to remove the characters
// having odd frequencies in the string
import java.util.*;
 
class GFG
{
      
    // Function to remove the characters which
    // have odd frequencies in the string
    static String removeOddFrequencyCharacters(String s)
    {
        // Create a map to store the
        // frequency of each character
        HashMap<Character, Integer> m = new HashMap<Character,Integer>();
        for (int i = 0; i < s.length(); i++) {
            char p = s.charAt(i);
            Integer count = m.get(p);
            if( count == null)
            {
                count=0;
                m.put(p,1);
            }
            else
                m.put(p,count + 1);
        }
      
        // To store the new string
        String new_string = "";
      
        // Remove the characters which
        // have odd frequencies
        for (int i = 0; i < s.length(); i++) {
      
            // If the character has
            // odd frequency then skip
            if ((m.get(s.charAt(i))& 1)==1)
                continue;
      
            // Else concatenate the
            // character to the new string
            new_string += s.charAt(i);
        }
      
        // Return the modified string
        return new_string;
    }
      
    // Driver code
    public static void main(String []args)
    {
        String str = "geeksforgeeks";
      
        // Remove the characters which
        // have odd frequencies
        str = removeOddFrequencyCharacters(str);
        System.out.print(str);
    }
}
 
// This is contributed by chitranayal


Python3




# Python3 program to remove the characters
# having odd frequencies in the string
 
# Function to remove the characters which
# have odd frequencies in the string
def removeOddFrequencyCharacters(s):
     
    # Create a map to store the
    # frequency of each character
    m = dict()
    for i in s:
        m[i] = m.get(i, 0) + 1
 
    # To store the new string
    new_s = ""
 
    # Remove the characters which
    # have odd frequencies
    for i in s:
 
        # If the character has
        # odd frequency then skip
        if (m[i] & 1):
            continue
 
        # Else concatenate the
        # character to the new string
        new_s += i
 
    # Return the modified string
    return new_s
 
# Driver code
if __name__ == '__main__':
    str = "geeksforgeeks"
 
    # Remove the characters which
    # have odd frequencies
    str = removeOddFrequencyCharacters(str)
    print(str)
 
# This code is contributed by mohit kumar 29


C#




// C# program to remove the characters
// having odd frequencies in the string
using System;
using System.Collections.Generic;
 
class GFG{
       
// Function to remove the characters which
// have odd frequencies in the string
static string removeOddFrequencyCharacters(string s)
{
     
    // Create a map to store the
    // frequency of each character
    Dictionary<char,
               int> m = new Dictionary<char,
                                       int>();
     
    for(int i = 0; i < s.Length; i++)
    {
        char p = s[i];
         
        if (m.ContainsKey(p))
        {
            m[p]++;
        }
        else
        {
            m[p] = 1;
        }
    }
   
    // To store the new string
    string new_string = "";
   
    // Remove the characters which
    // have odd frequencies
    for(int i = 0; i < s.Length; i++)
    {
         
        // If the character has
        // odd frequency then skip
        if ((m[s[i]] & 1) == 1)
            continue;
   
        // Else concatenate the
        // character to the new string
        new_string += s[i];
    }
   
    // Return the modified string
    return new_string;
}
   
// Driver code
public static void Main(string []args)
{
    string str = "geeksforgeeks";
   
    // Remove the characters which
    // have odd frequencies
    str = removeOddFrequencyCharacters(str);
     
    Console.Write(str);
}
}
 
// This code is contributed by rutvik_56


Javascript




<script>
 
// Javascript program to remove the characters
// having odd frequencies in the string
 
    // Function to remove the characters which
    // have odd frequencies in the string
    function removeOddFrequencyCharacters(s)
    {
        // Create a map to store the
        // frequency of each character
        let m = new Map();
        for (let i = 0; i < s.length; i++) {
            let p = s[i];
            let count = m.get(p);
            if( count == null)
            {
                count=0;
                m.set(p,1);
            }
            else
                m.set(p,count + 1);
        }
       
        // To store the new string
        let new_string = "";
       
        // Remove the characters which
        // have odd frequencies
        for (let i = 0; i < s.length; i++) {
       
            // If the character has
            // odd frequency then skip
            if ((m.get(s[i])& 1)==1)
                continue;
       
            // Else concatenate the
            // character to the new string
            new_string += s[i];
        }
       
        // Return the modified string
        return new_string;
    }
 
// Driver code
     
      let str = "geeksforgeeks";
       
        // Remove the characters which
        // have odd frequencies
        str = removeOddFrequencyCharacters(str);
        document.write(str);
                                                                                 
</script>


Output

geeksgeeks






Time Complexity: O(n), where n is the length of the given string.
Auxiliary Space: O(n)

Approach: Bit Manipulation

Steps for the above approach:

  • Create a bit vector of size 26 (assuming the string contains only lowercase alphabets) to store the parity of each character’s frequency.
  • Traverse the string and toggle the corresponding bit in the bit vector for each character.
  • Iterate over the string again and append the characters to a new result string based on the bit value in the bit vector.
  • Return the result string as the output.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <string>
using namespace std;
 
string removeCharactersWithOddFrequencies(string str) {
    int bitVector = 0;
 
    for (char character : str) {
        // Get the index of the character (assuming lowercase alphabets)
        int index = character - 'a';
        // Toggle the corresponding bit in the bit vector
        bitVector ^= (1 << index);
    }
 
    string result = "";
 
    for (char character : str) {
        // Get the index of the character (assuming lowercase alphabets)
        int index = character - 'a';
        if (!(bitVector & (1 << index))) { // Check if the bit is not set
            result += character;
        }
    }
 
    return result;
}
 
int main() {
    string input_str = "geeksforgeeks";
    string output_str = removeCharactersWithOddFrequencies(input_str);
    cout << output_str << endl;
 
    return 0;
}


Java




public class RemoveCharactersWithOddFrequencies {
    static String
    removeCharactersWithOddFrequencies(String str)
    {
        int bitVector = 0;
 
        for (char character : str.toCharArray()) {
            // Get the index of the character (assuming
            // lowercase alphabets)
            int index = character - 'a';
            // Toggle the corresponding bit in the bit
            // vector
            bitVector ^= (1 << index);
        }
 
        StringBuilder result = new StringBuilder();
 
        for (char character : str.toCharArray()) {
            // Get the index of the character (assuming
            // lowercase alphabets)
            int index = character - 'a';
            if ((bitVector & (1 << index))
                == 0) { // Check if the bit is not set
                result.append(character);
            }
        }
 
        return result.toString();
    }
 
    public static void main(String[] args)
    {
        String input_str = "geeksforgeeks";
        String output_str
            = removeCharactersWithOddFrequencies(input_str);
        System.out.println(output_str);
    }
}


Python




# Python program to remove the characters
# having odd frequencies in the string
 
 
def removeCharactersWithOddFrequencies(str):
    bitVector = 0
 
    for character in str:
        # Get the index of the character (assuming lowercase alphabets)
        index = ord(character) - ord('a')
        # Toggle the corresponding bit in the bit vector
        bitVector ^= (1 << index)
 
    result = ""
 
    for character in str:
        # Get the index of the character (assuming lowercase alphabets)
        index = ord(character) - ord('a')
        if not (bitVector & (1 << index)):  # Check if the bit is not set
            result += character
 
    return result
 
 
# Driver Code
input_str = "geeksforgeeks"
output_str = removeCharactersWithOddFrequencies(input_str)
print(output_str)


C#




using System;
 
namespace RemoveCharactersWithOddFrequencies
{
    class Program
    {
        static string RemoveCharactersWithOddFrequencies(string str)
        {
            int bitVector = 0;
 
            foreach (char character in str)
            {
                // Get the index of the character (assuming lowercase alphabets)
                int index = character - 'a';
                // Toggle the corresponding bit in the bit vector
                bitVector ^= (1 << index);
            }
 
            string result = "";
 
            foreach (char character in str)
            {
                // Get the index of the character (assuming lowercase alphabets)
                int index = character - 'a';
                if ((bitVector & (1 << index)) == 0) // Check if the bit is not set
                {
                    result += character;
                }
            }
 
            return result;
        }
 
        static void Main(string[] args)
        {
            string input_str = "geeksforgeeks";
            string output_str = RemoveCharactersWithOddFrequencies(input_str);
            Console.WriteLine(output_str);
 
            // Pause execution to see the result
            Console.ReadKey();
        }
    }
}


Javascript




function removeCharactersWithOddFrequencies(str) {
    let bitVector = 0;
 
    for (let i = 0; i < str.length; i++) {
        let character = str[i];
        // Get the index of the character (assuming lowercase alphabets)
        let index = character.charCodeAt(0) - 'a'.charCodeAt(0);
        // Toggle the corresponding bit in the bit vector
        bitVector ^= (1 << index);
    }
 
    let result = "";
 
    for (let i = 0; i < str.length; i++) {
        let character = str[i];
        // Get the index of the character (assuming lowercase alphabets)
        let index = character.charCodeAt(0) - 'a'.charCodeAt(0);
        if (!(bitVector & (1 << index))) {  // Check if the bit is not set
            result += character;
        }
    }
 
    return result;
}
 
// Driver Code
let input_str = "geeksforgeeks";
let output_str = removeCharactersWithOddFrequencies(input_str);
console.log(output_str);


Output:

geeksgeeks

Time Complexity:  O(N), where N is the length of the input string. 

Auxiliary Space: O(1)



Last Updated : 04 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads