Java Program to remove odd frequency characters in a string

In this tutorial, we are going to remove the characters from a string that appears an odd number of times in it. We are going to use HashMap in JAVA to improve our time complexity to O(n).

Using HashMap in Java to make the task simpler

We are just inserting the characters with their frequencies in the hashmap by iterating over the characters of the input string. Then again iterating over the string characters and checking if the frequency is odd then add it to the result string. So let us understand this through the example.

Java Program to remove odd frequency characters in a string

Now let us go through the code in JAVA.

import java.util.*;
import java.lang.*;
import java.io.*;


class Game
{
  public static void main (String[] args) throws java.lang.Exception
  {
    String s = "invertebrates";
      
    HashMap<Character, Integer> H= new HashMap<Character,Integer>();
    
        for (int i = 0; i < s.length(); i++) { 
            char ch = s.charAt(i); 
            Integer count = H.get(ch); 
            if( count == null) 
            { 
                count=0; 
                H.put(ch,1); 
            } 
            else 
                H.put(ch,count + 1); 
        } 
       
        String res = ""; 
        
        for (int i = 0; i < s.length(); i++) { 
       
            if ((H.get(s.charAt(i))& 1)==1) 
                continue; 

            res += s.charAt(i); 
        } 
       
       System.out.println(res);
    
    
  }
}
Output : rtrt

I hope you got it. Comment below for doubts.

Leave a Reply

Your email address will not be published. Required fields are marked *