Java Program to Find Most Frequent Character
HashMap and then finds the character with the highest count by iterating through the map entries.Examples
How to Think About It
Algorithm
Code
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
Initialize countMap
countMap is empty {}
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}
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
Result
Most frequent character is 'l'
| Character | Count |
|---|---|
| h | 1 |
| e | 1 |
| l | 2 |
| o | 1 |
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
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); } }
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); } }
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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| HashMap counting | O(n) | O(k) | General strings with any characters |
| Array counting | O(n) | O(1) | ASCII characters, faster access |
| Java Streams | O(n) | O(k) | Concise code, modern Java |