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:

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

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: