Find Maximum and Minimum occurring character in a String in Java

In this tutorial, we will see how to find maximum and minimum occurring character in a string through a Java code. This guide provides a step-by-step explanation and sample code.
aabbbccc
In the above example, character ‘a’ occurred minimum number of times (i.e 2 times) compared to characters ‘b’ and ‘c’. Character ‘c’ occurred maximum number of times(i.e 3 times).

Algorithm:

Step 1: Create an array to store the frequency of each character.
Step 2: Iterate over the string and for each character, increase the corresponding index in the frequency array.
Step 3: Consider two variables to store the maximum and minimum frequencies and their corresponding characters.
Step 4: Traverse the frequency array to find the maximum and minimum values.
Step 5: Display the most and least frequent character in a string.

Sample Java Code:

class MaxMinChar {
    public static void main(String[] args) {
        String str="an apple";
        int n=str.length();
        int[] freq=new int[256];
        for(int i=0;i<n;i++) {
            char ch=str.charAt(i);
            if(ch!=' ') {
                freq[ch]++;
            }
        }
        int max=-1;
        int min=Integer.MAX_VALUE;
        char maxChar=' ';
        char minChar=' ';
        for(int i=0;i<256;i++) {
            if(freq[i]>0) {
                if(freq[i]>max) {
                    max=freq[i];
                    maxChar=(char)i;
                }
                if(freq[i]<min) {
                    maxChar=freq[i];
                    minChar=(char)i;
                }
            }
        }
        System.out.println("Maximum Occurring Character is: "+maxChar);
        System.out.println("Minimum Occurring Character is: "+minChar);
    }
}

Output:

Maximum Occurring Character is: a
Minimum Occurring Character is: e

 

Leave a Comment

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

Scroll to Top