Java String Program · S26
Find the Most Frequent Character in a String in Java
Count every character and pick the one with the highest count. Defining what happens on a tie is what makes the answer predictable.
Problem Statement
Write a method that returns the character that appears most often in a string. Spaces are ignored and the comparison is case-sensitive.
If several characters share the highest count, return the one that appears first in the string. For an empty or blank string, return null (printed as none).
Input/Output Examples
"programming"OutputrExplanation: r, g and m all appear twice; r appears first."Mississippi"OutputiExplanation: i and s both appear four times; i comes first."aAbB"OutputaExplanation: all four characters appear once, so the first one wins.Visual Explanation
"programming", r, g and m all reach the highest count of 2. Scanning from the left, r (purple) is the first of them.The first pass finds the counts and the highest count. The second pass walks the string from the left and stops at the first character with that count, which settles any tie by position.
Approaches
Both approaches apply the same tie rule. One uses an ASCII array; the other a map and a stream.
Approach 1: Counting Array, Two Passes (Recommended)
Idea: count characters in an int[128] while tracking the highest count, then return the first character in the string that has it.
- Skip spaces; increase
counts[c]and updatebest. - Walk the string again from the start.
- Return the first character whose count equals
best.
Time: O(n) · Space: O(1). The array has a fixed 128 slots (ASCII).
Approach 2: LinkedHashMap and Stream max()
Idea: count in a LinkedHashMap (first-appearance order), then take the entry with the largest value.
- Count characters with
merge(). - Stream the entries and call
max(Map.Entry.comparingByValue()). - Map the result to its key, or
nullif the map is empty.
Time: O(n) · Space: O(k).
Java Solutions
Each tab is a complete program that runs on Java 17 or later. Both programs print the same output for the same inputs.
Approach 1: Counting Array, Two Passes (Recommended)
Fast and allocation-free. For non-ASCII text, replace the array with a map.
public class MostFrequentArray {
// ASCII only; on a tie, the character that appears first in the string wins
static Character mostFrequent(String text) {
int[] counts = new int[128];
int best = 0;
for (char c : text.toCharArray()) {
if (c != ' ') {
best = Math.max(best, ++counts[c]);
}
}
for (char c : text.toCharArray()) {
if (c != ' ' && counts[c] == best) {
return c; // first character that reaches the top count
}
}
return null; // empty or only spaces
}
public static void main(String[] args) {
String[] inputs = {"programming", "Mississippi", "aAbB", " "};
for (String s : inputs) {
Character c = mostFrequent(s);
System.out.println("\"" + s + "\" -> " + (c == null ? "none" : c));
}
}
}
"programming" -> r "Mississippi" -> i "aAbB" -> a " " -> none
Time complexity: O(n) · Space complexity: O(1).
Approach 2: LinkedHashMap and Stream max()
When two entries are equal, Stream.max() keeps the earlier one, so the tie rule matches the array version.
import java.util.LinkedHashMap;
import java.util.Map;
public class MostFrequentStream {
// LinkedHashMap keeps first-appearance order, and Stream.max() keeps the first of equal elements
static Character mostFrequent(String text) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : text.toCharArray()) {
if (c != ' ') {
counts.merge(c, 1, Integer::sum);
}
}
return counts.entrySet().stream()
.max(Map.Entry.comparingByValue())
.map(Map.Entry::getKey)
.orElse(null);
}
public static void main(String[] args) {
String[] inputs = {"programming", "Mississippi", "aAbB", " "};
for (String s : inputs) {
Character c = mostFrequent(s);
System.out.println("\"" + s + "\" -> " + (c == null ? "none" : c));
}
}
}
"programming" -> r "Mississippi" -> i "aAbB" -> a " " -> none
Time complexity: O(n) · Space complexity: O(k).
Complexity Analysis
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Counting Array, Two Passes | O(n) | O(1) |
| LinkedHashMap and Stream max() | O(n) | O(k) |
Here n is the length of the string and k is the number of distinct characters. Both approaches count in one pass and then search a structure of at most n elements.
Interview Tips and Recommended Approach
- Always state the tie rule. Without it, two correct programs can return different answers.
- Know why a plain
HashMapis risky. Its iteration order is not defined, so ties could be broken differently from run to run of the code base. - Use
++counts[c]to track the maximum in the same pass. It saves a separate scan over the array. - Ask about case and spaces. They change the answer for inputs like
"Aa a".
Recommended Approach: Counting Array, Two Passes
Why: it runs in linear time with a fixed-size array and makes the tie rule explicit through the second pass over the string.