Open In App

Remove even frequency characters from the string

Last Updated : 21 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a string ‘str’, the task is to remove all the characters from the string that have even frequencies.

Examples: 

Input: str = "aabbbddeeecc"
Output: bbbeee
The characters a, d, c have even frequencies
So, they are removed from the string.

Input: str = "zzzxxweeerr"
Output: zzzweee

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 even frequencies with the help of the map.
  • Ignore all those characters which have even frequencies and store the rest in a new string.
  • Finally, display the new string.

Below is the implementation of the above approach:  

C++




// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Function that removes the
// characters which have even
// frequencies in the string
void solve(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 even frequencies
    for (int i = 0; i < s.length(); i++) {
 
        // if the character has
        // even frequency then skip
        if (m[s[i]] % 2 == 0)
            continue;
 
        // else concatenate the
        // character to the new string
        new_string += s[i];
    }
 
    // display the modified string
    cout << new_string << endl;
}
 
// Driver code
int main()
{
    string s = "aabbbddeeecc";
 
    // remove the characters which
    // have even frequencies
    solve(s);
 
    return 0;
}


Java




// Java implementation of the approach
import java.util.*;
 
class GFG
{
    // Function that removes the
    // characters which have even
    // frequencies in the string
    static void solve(String s)
    {
        // create a map to store the
        // frequency of each character
        HashMap<Character, Integer> m = new HashMap<>();
         
        for (int i = 0; i < s.length(); i++)
        {
            if(m.containsKey(s.charAt(i)))
                        m.put(s.charAt(i),
                        m.get(s.charAt(i)) + 1);
            else
                m.put(s.charAt(i), 1);
        }
     
        // to store the new string
        String new_string = "";
     
        // remove the characters which
        // have even frequencies
        for (int i = 0; i < s.length(); i++)
        {
     
            // if the character has
            // even frequency then skip
            if (m.get(s.charAt(i)) % 2 == 0)
                continue;
     
            // else concatenate the
            // character to the new string
            new_string = new_string + s.charAt(i);
        }
     
        // display the modified string
        System.out.println(new_string);
    }
     
    // Driver code
    public static void main(String []args)
    {
        String s = "aabbbddeeecc";
     
        // remove the characters which
        // have even frequencies
        solve(s);
    }
}
 
// This code is contributed by ihritik


Python3




# Python3 implementation of
# above approach
 
# Function that removes the
# characters which have even
# frequencies in the string
def solve(s):
     
    # create a map to store the
    # frequency of each character
    m = dict()
    for i in range(len(s)):
        if s[i] in m:
            m[s[i]] = m[s[i]]+1
        else:
            m[s[i]] = 1
             
    # to store the new string
    new_string = ""
     
    # remove the characters which
    # have even frequencies
    for i in range(len(s)):
         
        # if the character has
        # even frequency then skip
        if m[s[i]]%2 == 0:
            continue
         
        # else concatenate the
        # character to the new string
        new_string = new_string+s[i]
         
    # display the modified string
    print(new_string)
     
#Driver code
if __name__=='__main__':
    s = "aabbbddeeecc"
 
# remove the characters which
# have even frequencies
    solve(s)
 
# this code is contributed by
# Shashank_Sharma


C#




// C# implementation of the approach
using System;
using System.Collections.Generic;
 
class GFG
{
    // Function that removes the
    // characters which have even
    // frequencies in the string
    static void solve(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++)
        {
            if(m.ContainsKey(s[i]))
            {
                var val = m[s[i]];
                m.Remove(s[i]);
                m.Add(s[i], val + 1);
                 
            }        
            else
                m.Add(s[i], 1);
        }
     
        // to store the new string
        String new_string = "";
     
        // remove the characters which
        // have even frequencies
        for (int i = 0; i < s.Length; i++)
        {
     
            // if the character has
            // even frequency then skip
            if (m[s[i]] % 2 == 0)
                continue;
     
            // else concatenate the
            // character to the new string
            new_string = new_string + s[i];
        }
     
        // display the modified string
        Console.WriteLine(new_string);
    }
     
    // Driver code
    public static void Main(String []args)
    {
        String s = "aabbbddeeecc";
     
        // remove the characters which
        // have even frequencies
        solve(s);
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
 
    // JavaScript program for the above approach
 
     // Function that removes the
    // characters which have even
    // frequencies in the string
    function solve(s)
    {
        // create a map to store the
        // frequency of each character
        let m = new Map();
         
        for (let i = 0; i < s.length; i++)
        {
            if(m.has(s[i]))
                        m.set(s[i],
                        m.get(s[i]) + 1);
            else
                m.set(s[i], 1);
        }
     
        // to store the new string
        let new_string = "";
     
        // remove the characters which
        // have even frequencies
        for (let i = 0; i < s.length; i++)
        {
     
            // if the character has
            // even frequency then skip
            if (m.get(s[i]) % 2 == 0)
                continue;
     
            // else concatenate the
            // character to the new string
            new_string = new_string + s[i];
        }
     
        // display the modified string
        document.write(new_string);
    }
 
// Driver Code
 
        let s = "aabbbddeeecc";
     
        // remove the characters which
        // have even frequencies
        solve(s);
 
</script>   


Output

bbbeee

Complexity Analysis:

  • Time Complexity: O(N) 
  • Auxiliary Space: O(N)

Method #2: Using Built-in Python Functions 

  • Calculate the frequency of all characters using Counter() function.
  • Then, traverse the string and find out which characters have even frequencies with the help of the map.
  • Ignore all those characters which have even frequencies and store the rest in a new string.
  • Finally, display the new string.

Below is the implementation:

C++




#include <iostream>
#include <unordered_map>
using namespace std;
 
// Function to remove characters with even frequencies
void removeEven(string s)
{
 
  // Calculate the frequency of each character
  unordered_map<char, int> freq;
  for (int i = 0; i < s.length(); i++) {
    char ch = s[i];
    freq[ch]++;
  }
 
  // Remove the characters with even frequencies
  string newString = "";
  for (int i = 0; i < s.length(); i++) {
    char ch = s[i];
    if (freq[ch] % 2 != 0) {
      newString += ch;
    }
  }
 
  // Display the modified string
  cout << newString << endl;
}
 
// Driver code
int main() {
  string s = "aabbbddeeecc";
  removeEven(s);
  return 0;
}


Java




import java.util.HashMap;
import java.util.Map;
 
public class Main {
   
  // Function to remove characters with even frequencies
  static void removeEven(String s) {
     
    // Calculate the frequency of each character
    Map<Character, Integer> freq = new HashMap<>();
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      freq.put(ch, freq.getOrDefault(ch, 0) + 1);
    }
     
    // Remove the characters with even frequencies
    StringBuilder newString = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
      char ch = s.charAt(i);
      if (freq.get(ch) % 2 != 0) {
        newString.append(ch);
      }
    }
     
    // Display the modified string
    System.out.println(newString.toString());
  }
   
  // Driver code
  public static void main(String[] args) {
    String s = "aabbbddeeecc";
    removeEven(s);
  }
}


Python3




# Python3 implementation of
# above approach
from collections import Counter
 
# Function that removes the
# characters which have even
# frequencies in the string
def removeEven(s):
 
    # Calculate the frequency using Counter function
    # to store the new string
    m = Counter(s)
    new_string = ""
 
    # Remove the characters which
    # have even frequencies
    for i in range(len(s)):
        if(m[s[i]] % 2 != 0):
           
            # Concatenate the character to the new string
            new_string = new_string+s[i]
 
    # display the modified string
    print(new_string)
 
 
# Driver code
if __name__ == '__main__':
    s = "aabbbddeeecc"
 
# remove the characters which
# have even frequencies
    removeEven(s)
 
# this code is contributed by vikkycirus


Javascript




// JavaScript implementation of the above approach
function removeEven(s)
{
 
// Calculate the frequency using Counter function
// to store the new string
let m = new Map();
let new_string = "";
 
// Count the frequency of each character
for (let i = 0; i < s.length; i++) {
    if (m.has(s[i])) {
        m.set(s[i], m.get(s[i]) + 1);
    } else {
        m.set(s[i], 1);
    }
}
 
// Remove the characters which have even frequencies
for (let i = 0; i < s.length; i++)
 
{
 
    if (m.get(s[i]) % 2 != 0) {
    // Concatenate the character to the new string
        new_string = new_string + s[i];
    }
}
 
// Display the modified string
console.log(new_string);
}
 
// Driver code
let s = "aabbbddeeecc";
 
// Remove the characters which have even frequencies
removeEven(s);
 
// This code is contributed by codebraxnzt


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
public class MainClass {
    // Function to remove characters with even frequencies
    static void RemoveEven(string s)
    {
        // Calculate the frequency of each character
        Dictionary<char, int> freq
            = new Dictionary<char, int>();
        for (int i = 0; i < s.Length; i++) {
            char ch = s[i];
            if (freq.ContainsKey(ch)) {
                freq[ch]++;
            }
            else {
                freq[ch] = 1;
            }
        }
        // Remove the characters with even frequencies
        string newString = "";
        for (int i = 0; i < s.Length; i++) {
            char ch = s[i];
            if (freq[ch] % 2 != 0) {
                newString += ch;
            }
        }
 
        // Display the modified string
        Console.WriteLine(newString);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        string s = "aabbbddeeecc";
        RemoveEven(s);
    }
}


Output

bbbeee

Complexity Analysis:

  • Time Complexity: O(N) 
  • Auxiliary Space: O(N)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads