Most Frequent Character

Java coding interview problem for Character Problems: Most Frequent Character.

Finding the Most Frequent Character is one of the most commonly asked String interview questions.

Although it appears straightforward, this problem introduces several important concepts used throughout Data Structures and Algorithms.

It helps you understand:

  • HashMap
  • Frequency Counting
  • Arrays
  • ASCII
  • String Traversal
  • Searching
  • Time Complexity

Many advanced interview problems are based on this concept, including:

  • Character Frequency
  • First Non-Repeating Character
  • First Repeating Character
  • Top K Frequent Elements
  • Sort Characters by Frequency
  • Group Anagrams

Mastering this problem makes many string interview questions significantly easier.


Problem Statement

Given a string,

find the character that appears the maximum number of times.

If multiple characters have the same highest frequency,

the interview may ask you to:

  • Return the first occurring character.
  • Return any one of them.
  • Return all characters having maximum frequency.

Always clarify the requirement before coding.


Example 1

Input

banana

Output

a

Frequency

a → 3

Example 2

Input

mississippi

Output

i

Frequency

i → 4

s → 4

If the interviewer asks for the first occurring maximum frequency character,

the answer is

i

Example 3

Input

programming

Output

g

Frequency

g → 2

Example 4

Input

aaaaabbbbcc

Output

a

Frequency

a → 5

What is the Most Frequent Character?

The most frequent character is

The character that appears the highest number of times in a string.

Example

apple

Frequency

a → 1

p → 2

l → 1

e → 1

Most Frequent

p

Another Example

committee

Frequency

c → 1

o → 1

m → 2

i → 1

t → 2

e → 2

Depending on interview requirements,

you may return

m

or

t

or

e

or all three.


Why is this Question Asked in Interviews?

Interviewers use this problem to evaluate your understanding of:

  • HashMap
  • Arrays
  • Frequency Counting
  • Searching
  • Traversing Strings
  • Time Complexity
  • Edge Cases

It also serves as the basis for many advanced interview problems.


Real-World Applications

Finding the most frequent character is widely used in software systems.


Text Analytics

Find the most common letters.


Search Engines

Analyze popular search keywords.


Data Compression

Frequently occurring symbols receive shorter codes.

(Huffman Coding)


Natural Language Processing (NLP)

Determine commonly used characters.


Cyber Security

Detect suspicious repetitive patterns.


DNA Sequence Analysis

Identify repeated nucleotide patterns.


Understanding Frequency Counting

Consider

banana

Initially

{}

Read

b

Store

b → 1

Read

a
b → 1

a → 1

Read

n
b → 1

a → 1

n → 1

Read

a

Increase

a → 2

Read

n

Increase

n → 2

Read

a

Increase

a → 3

Final

b → 1

a → 3

n → 2

Maximum Frequency

a

Frequency Table Visualization

Input

banana
Character Frequency
b 1
a 3
n 2

Maximum

a → 3

Another Example

Input

apple
Character Frequency
a 1
p 2
l 1
e 1

Maximum

p → 2

Mathematical Concept

Frequency

Frequency(Character)

=

Occurrences

Most Frequent Character

Character

having

Maximum Frequency

Mathematically

max(Frequency)

ASCII Frequency Visualization

Input

banana
ASCII

b

↓

98

↓

1
a

↓

97

↓

3
n

↓

110

↓

2

Maximum

a

Dry Run

Input

banana

Initial

Map = {}

Maximum

None

Read

b
{b=1}

Maximum

b

Read

a
{b=1,a=1}

Maximum

Tie


Read

n
{b=1,a=1,n=1}

Read

a
{b=1,a=2,n=1}

Maximum

a

Read

n
{b=1,a=2,n=2}

Read

a
{b=1,a=3,n=2}

Final Answer

a

Approach 1 — Using HashMap (Recommended)

This is the most common interview solution.

The idea is:

  1. Count every character.
  2. Find the maximum frequency.

Algorithm

  1. Create a HashMap.
  2. Traverse the string.
  3. Update frequencies.
  4. Traverse the HashMap.
  5. Track the maximum frequency.
  6. Return the corresponding character.

Java Program

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

public class MostFrequentCharacterHashMap {

    public static char findMostFrequent(String text) {

        Map<Character, Integer> map =
                new HashMap<>();

        for (char ch : text.toCharArray()) {

            map.put(ch,
                    map.getOrDefault(ch, 0) + 1);

        }

        char result = '\0';
        int max = 0;

        for (Map.Entry<Character, Integer> entry
                : map.entrySet()) {

            if (entry.getValue() > max) {

                max = entry.getValue();
                result = entry.getKey();

            }

        }

        return result;

    }

    public static void main(String[] args) {

        System.out.println(
                findMostFrequent("banana"));

    }

}

Output

a

Step-by-Step Code Explanation

Create HashMap

Map<Character,Integer> map =
        new HashMap<>();

Update frequency

map.put(ch,
        map.getOrDefault(ch,0)+1);

Track maximum

if(entry.getValue() > max)

Update

max = entry.getValue();

result = entry.getKey();

Return

result

Dry Run of HashMap Approach

Input

apple
Character Map
a {a=1}
p {a=1,p=1}
p {a=1,p=2}
l {a=1,p=2,l=1}
e {a=1,p=2,l=1,e=1}

Maximum

p

Advantages

  • Most common interview solution.
  • Easy to explain.
  • Supports Unicode.
  • O(n) time complexity.
  • Dynamic storage.

Drawbacks

  • Additional memory required.
  • HashMap does not preserve insertion order.

Approach 2 — Using Frequency Array (ASCII)

If the input contains only ASCII characters,

an array is faster than a HashMap.

Each ASCII value acts as the array index.


Visualization

Input

banana

Array

frequency['a']

↓

3
frequency['b']

↓

1
frequency['n']

↓

2

Maximum

a

Algorithm

  1. Create an array of size 256.
  2. Count every character.
  3. Traverse the array.
  4. Find the maximum frequency.
  5. Return the corresponding character.

Java Program

public class MostFrequentCharacterArray {

    public static char findMostFrequent(String text) {

        int[] frequency =
                new int[256];

        for (char ch : text.toCharArray()) {

            frequency[ch]++;

        }

        int max = 0;
        char result = '\0';

        for (int i = 0; i < frequency.length; i++) {

            if (frequency[i] > max) {

                max = frequency[i];
                result = (char) i;

            }

        }

        return result;

    }

    public static void main(String[] args) {

        System.out.println(
                findMostFrequent("banana"));

    }

}

Output

a

Step-by-Step Code Explanation

Create frequency array

int[] frequency =
        new int[256];

Count characters

frequency[ch]++;

Find maximum

if(frequency[i] > max)

Update

max = frequency[i];

result = (char)i;

Time & Space Complexity

Approach Time Extra Space
HashMap O(n) O(k)
Frequency Array O(n) O(1)*

Where:

  • n = Length of the string
  • k = Number of distinct characters

*For a fixed ASCII character set, the array size (256) is constant, so the extra space is considered O(1).


Comparison of Approaches

Feature HashMap Frequency Array
Interview Friendly ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
Performance ⭐⭐⭐⭐ ⭐⭐⭐⭐⭐
Unicode Support ✅ ❌
Dynamic Size ✅ ❌
Memory Efficient (ASCII) ❌ ✅

Advantages

  • Both approaches run in O(n) time.
  • HashMap supports dynamic and Unicode character sets.
  • Frequency Array is extremely fast for ASCII strings.
  • Both are widely accepted interview solutions.

Drawbacks

  • HashMap requires extra memory.
  • Frequency Array is limited to ASCII unless expanded.
  • Neither approach preserves insertion order when resolving ties.

Approach 3 — Using LinkedHashMap (First Occurrence Tie-Breaking)

Sometimes interviewers ask:

If multiple characters have the same maximum frequency, return the character that appears first in the string.

A normal HashMap does not preserve insertion order.

A LinkedHashMap does.


Example

Input

mississippi

Frequency

m → 1

i → 4

s → 4

p → 2

Maximum Frequency

4

Both

i

s

appear four times.

Since

i

appears first,

Output

i

Why LinkedHashMap?

LinkedHashMap remembers the order in which keys were inserted.

Insertion Order

m

↓

i

↓

s

↓

p

Algorithm

  1. Create LinkedHashMap.
  2. Count frequencies.
  3. Traverse LinkedHashMap.
  4. Return first character having maximum frequency.

Java Program

import java.util.LinkedHashMap;
import java.util.Map;

public class MostFrequentCharacterLinkedHashMap {

    public static char findMostFrequent(String text) {

        Map<Character, Integer> map =
                new LinkedHashMap<>();

        for (char ch : text.toCharArray()) {

            map.put(ch,
                    map.getOrDefault(ch, 0) + 1);

        }

        char result = '\0';
        int max = 0;

        for (Map.Entry<Character, Integer> entry : map.entrySet()) {

            if (entry.getValue() > max) {

                max = entry.getValue();
                result = entry.getKey();

            }

        }

        return result;

    }

    public static void main(String[] args) {

        System.out.println(
                findMostFrequent("mississippi"));

    }

}

Output

i

Advantages

  • Maintains insertion order.
  • Easy to understand.
  • Excellent interview solution.

Drawbacks

  • Slightly more memory than HashMap.
  • Slightly slower than HashMap.

Approach 4 — Using Java Streams

Java Streams provide a concise functional programming solution.

This approach groups characters and counts their occurrences.


Algorithm

  1. Convert string into stream.
  2. Group identical characters.
  3. Count frequencies.
  4. Find maximum frequency.

Java Program

import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class MostFrequentCharacterStreams {

    public static char findMostFrequent(String text) {

        Map<Character, Long> frequency =
                text.chars()
                        .mapToObj(c -> (char) c)
                        .collect(Collectors.groupingBy(
                                Function.identity(),
                                LinkedHashMap::new,
                                Collectors.counting()));

        return frequency.entrySet()
                .stream()
                .max(Comparator.comparingLong(
                        Map.Entry::getValue))
                .get()
                .getKey();

    }

    public static void main(String[] args) {

        System.out.println(
                findMostFrequent("banana"));

    }

}

Output

a

Advantages

  • Modern Java.
  • Functional programming.
  • Very concise.

Drawbacks

  • Additional Stream overhead.
  • Harder for beginners.
  • Rarely expected during live coding interviews.

Approach 5 — Using TreeMap (Sorted Frequency Analysis)

Sometimes interviewers ask for the result to be processed in sorted order.

TreeMap automatically sorts keys alphabetically.


Example

Input

banana

TreeMap

a → 3

b → 1

n → 2

Maximum

a

Algorithm

  1. Create TreeMap.
  2. Count frequencies.
  3. Traverse TreeMap.
  4. Find maximum frequency.

Java Program

import java.util.Map;
import java.util.TreeMap;

public class MostFrequentCharacterTreeMap {

    public static char findMostFrequent(String text) {

        Map<Character, Integer> map =
                new TreeMap<>();

        for (char ch : text.toCharArray()) {

            map.put(ch,
                    map.getOrDefault(ch, 0) + 1);

        }

        char result = '\0';
        int max = 0;

        for (Map.Entry<Character, Integer> entry : map.entrySet()) {

            if (entry.getValue() > max) {

                max = entry.getValue();
                result = entry.getKey();

            }

        }

        return result;

    }

    public static void main(String[] args) {

        System.out.println(
                findMostFrequent("banana"));

    }

}

Output

a

Advantages

  • Keys remain sorted.
  • No additional sorting required.
  • Useful for reports.

Drawbacks

  • Slower than HashMap.
  • Insertions take O(log k) time.

Unicode Considerations

Java String uses UTF-16 encoding.

Examples

こんにちは
नमस्ते
😊😊😂

The following approaches support general Java text:

  • HashMap
  • LinkedHashMap
  • TreeMap

For supplementary Unicode characters (such as many emoji), iterate over Unicode code points instead of individual char values.


Edge Cases

Input Expected Output
"" No Character
"a" a
"aaaa" a
"abc" Clarify tie-breaking rule
"AaAa" A or a depending on case sensitivity
" " (space)
null Handle appropriately

Time & Space Complexity

Approach Time Extra Space
HashMap O(n) O(k)
Frequency Array O(n) O(1)*
LinkedHashMap O(n) O(k)
Java Streams O(n) O(k)
TreeMap O(n log k) O(k)

Where

  • n = Length of the string
  • k = Number of distinct characters

*For a fixed ASCII character set, the frequency array size is constant, so its extra space is considered O(1).


Comparison of All Approaches

Approach Interview Friendly Performance Maintains Order Sorted Output Unicode Support Best Use Case
HashMap ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ❌ ❌ ✅ General interviews
Frequency Array ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐⭐ ❌ ❌ ❌ ASCII strings
LinkedHashMap ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ ✅ ❌ ✅ Tie-breaking by first occurrence
Java Streams ⭐⭐⭐⭐ ⭐⭐⭐ ✅ ❌ ✅ Modern Java applications
TreeMap ⭐⭐⭐⭐ ⭐⭐⭐ ❌ ✅ ✅ Sorted reports

Common Interview Mistakes

Mistake 1

Ignoring tie-breaking rules.

Example

abab

Both

a

b

occur twice.

Always ask whether to:

  • Return the first occurrence.
  • Return any character.
  • Return all tied characters.

Mistake 2

Using nested loops.

for(...)
    for(...)

This produces

O(n²)

HashMap provides an

O(n)

solution.


Mistake 3

Using Frequency Array for Unicode text.

Arrays of size 256 only work correctly for ASCII.


Mistake 4

Ignoring uppercase and lowercase differences.

A

a

are different characters unless specified otherwise.


Mistake 5

Not handling empty strings.

Always check

text == null || text.isEmpty()

before processing.


Interview Follow-up Questions

Q1. Why is HashMap the preferred solution?

Q2. How do you handle ties?

Q3. Why use LinkedHashMap instead of HashMap?

Q4. Why is TreeMap slower?

Q5. Which solution is fastest?

Q6. How would you support Unicode characters?

Q7. Can this be solved without collections?

Q8. How would you process a very large text file?

Q9. Can multiple characters have the highest frequency?

Q10. What is the overall space complexity?


Related Problems

  • Character Frequency
  • First Non-Repeating Character
  • First Repeating Character
  • Top K Frequent Elements
  • Sort Characters by Frequency
  • Valid Anagram
  • Group Anagrams
  • Longest Substring Without Repeating Characters

Key Takeaways

  • Finding the most frequent character is a classic frequency-counting interview problem.
  • HashMap is the recommended interview solution because it is simple, efficient, and supports Unicode.
  • Frequency Array is the fastest approach for ASCII-only strings.
  • LinkedHashMap is ideal when ties must be resolved using insertion order.
  • TreeMap automatically keeps keys sorted but has slower insertions.
  • Java Streams provide a concise functional programming alternative.

Frequently Asked Interview Questions

Q1. Which approach is best for interviews?

Use HashMap because it is simple, readable, efficient, and works for most real-world scenarios.


Q2. Which solution is the fastest?

For ASCII input, the Frequency Array approach is generally the fastest because array indexing is constant time.


Q3. Why use LinkedHashMap?

Use LinkedHashMap when multiple characters have the same highest frequency and the interviewer wants the first occurring one.


Q4. When should TreeMap be used?

Use TreeMap when the output must be sorted alphabetically without performing a separate sorting step.


Q5. Does HashMap preserve insertion order?

No.

HashMap does not guarantee insertion order.

Use LinkedHashMap for insertion order or TreeMap for sorted order.


Interview Tip

If an interviewer asks:

"Find the most frequent character in a string."

Start with the HashMap solution because it is the standard and most widely accepted approach.

Before coding, clarify these requirements:

  • Should uppercase and lowercase letters be treated as different characters?
  • If multiple characters have the same highest frequency, which one should be returned?
  • Should spaces and punctuation be counted?
  • Will the input contain only ASCII characters or full Unicode text?

After presenting the HashMap solution, discuss alternative implementations:

  1. HashMap (recommended)
  2. Frequency Array (ASCII optimization)
  3. LinkedHashMap (first-occurrence tie-breaking)
  4. Java Streams (functional programming)
  5. TreeMap (sorted output)

This demonstrates not only coding ability but also your understanding of algorithmic trade-offs and Java Collections Framework design.