Print maximum occurring character in a String

Objective– Given a string, write an algorithm to find the character in string which occurs maximum number of times. If more than one character has maximum and same count then print all of them

Example:

Input- tutorial horizon
Character: o has occurred max times:  3
----------------------
Input- abcabcdefabcab
Character: a has occurred max times:  4
Character: b has occurred max times:  4

Approach:

  • Use Hash Map. (Character as key and its count as value)
  • For every character in string, If character is present in hash map then increment its count in hash map else store the character as count 1.
  • Keep track of the maximum count was stored in map in separate variable.
  • At the end iterate through hash map and print all the characters which has maximum count .

Java Code:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
public class MaximumOccurringCharacter {
static void findMaximumOccurring(String input){
int maxCount =0;
HashMap<Character, Integer> map = new HashMap<>();
char[] chars = input.toCharArray();
for (int i = 0; i <chars.length ; i++) {
char c = chars[i];
if(map.containsKey(c)){
int count = map.get(c);
count++;
if(maxCount<count)
maxCount++;
map.put(c, count);
}else{
map.put(c, 1);
}
}
Set set = map.keySet();
Iterator<Character> iterator = set.iterator();
while(iterator.hasNext()){
char key = iterator.next();
//check count
if(map.get(key)==maxCount){
System.out.println("Character: " + key + " has occurred max times: " + maxCount);
}
}
}
public static void main(String[] args) {
String input = "tutorial horizon";
System.out.println("Input- " + input);
findMaximumOccurring(input);
System.out.println("———————-");
String input2 = "abcabcdefabcab";
System.out.println("Input- " + input2);
findMaximumOccurring(input2);
}
}

Output:

Input- tutorial horizon
Character: o has occurred max times:  3
----------------------
Input- abcabcdefabcab
Character: a has occurred max times:  4
Character: b has occurred max times:  4