0
0
JavaProgramBeginner · 2 min read

Java Program to Find Most Frequent Character

Use a Java program that counts each character's occurrences with a HashMap and then finds the character with the highest count by iterating through the map entries.
📋

Examples

Inputhello
OutputMost frequent character: l
Inputaabbccddeeff
OutputMost frequent character: a
Inputxyz
OutputMost frequent character: x
🧠

How to Think About It

To find the most frequent character, first count how many times each character appears by going through the string once. Then, check which character has the highest count by comparing all counts. The character with the largest count is the most frequent.
📐

Algorithm

1
Get the input string.
2
Create a map to store character counts.
3
For each character in the string, increase its count in the map.
4
Find the character with the highest count by checking all map entries.
5
Return or print the character with the highest count.
💻

Code

java
import java.util.HashMap;
import java.util.Map;

public class MostFrequentChar {
    public static void main(String[] args) {
        String input = "hello";
        Map<Character, Integer> countMap = new HashMap<>();
        for (char c : input.toCharArray()) {
            countMap.put(c, countMap.getOrDefault(c, 0) + 1);
        }
        char maxChar = input.charAt(0);
        int maxCount = 0;
        for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
            if (entry.getValue() > maxCount) {
                maxChar = entry.getKey();
                maxCount = entry.getValue();
            }
        }
        System.out.println("Most frequent character: " + maxChar);
    }
}
🔍

Dry Run

Let's trace the input "hello" through the code

1

Initialize countMap

countMap is empty {}

2

Count characters

After 'h': {h=1} After 'e': {h=1, e=1} After 'l': {h=1, e=1, l=1} After second 'l': {h=1, e=1, l=2} After 'o': {h=1, e=1, l=2, o=1}

3

Find max character

maxChar = 'h', maxCount = 0 Check 'h': count=1 > 0, maxChar='h', maxCount=1 Check 'e': count=1 == maxCount, no change Check 'l': count=2 > 1, maxChar='l', maxCount=2 Check 'o': count=1 < maxCount, no change

4

Result

Most frequent character is 'l'

CharacterCount
h1
e1
l2
o1
💡

Why This Works

Step 1: Counting characters

We use a HashMap to store each character and how many times it appears, so we can quickly update and check counts.

Step 2: Finding the maximum

We check each entry in the map to find which character has the highest count by comparing counts with a stored maximum.

Step 3: Output the result

After finding the character with the highest count, we print it as the most frequent character.

🔄

Alternative Approaches

Using an array for ASCII characters
java
public class MostFrequentCharArray {
    public static void main(String[] args) {
        String input = "hello";
        int[] counts = new int[256];
        for (char c : input.toCharArray()) {
            counts[c]++;
        }
        int maxCount = 0;
        char maxChar = 0;
        for (int i = 0; i < counts.length; i++) {
            if (counts[i] > maxCount) {
                maxCount = counts[i];
                maxChar = (char) i;
            }
        }
        System.out.println("Most frequent character: " + maxChar);
    }
}
This approach is faster for ASCII but uses fixed extra space of size 256.
Using Java 8 Streams
java
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MostFrequentCharStream {
    public static void main(String[] args) {
        String input = "hello";
        Map<Character, Long> freq = input.chars()
            .mapToObj(c -> (char) c)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        char maxChar = freq.entrySet().stream()
            .max(Map.Entry.comparingByValue())
            .get()
            .getKey();
        System.out.println("Most frequent character: " + maxChar);
    }
}
This uses modern Java streams for concise code but may be less clear for beginners.

Complexity: O(n) time, O(k) space

Time Complexity

The program loops through the string once to count characters, which is O(n), and then loops through the map entries, which is O(k), where k is number of unique characters. Overall O(n).

Space Complexity

Extra space is used for the map storing counts of unique characters, which is O(k). For ASCII input, k is at most 256.

Which Approach is Fastest?

Using an array for ASCII characters is fastest due to direct indexing, but using a map is more flexible for Unicode.

ApproachTimeSpaceBest For
HashMap countingO(n)O(k)General strings with any characters
Array countingO(n)O(1)ASCII characters, faster access
Java StreamsO(n)O(k)Concise code, modern Java
💡
Use a map or array to count characters efficiently before finding the max.
⚠️
Forgetting to handle the case when multiple characters have the same highest frequency.