Return maximum occurring character in an input string - GeeksforGeeks

24 Feb, 2022
Write an efficient function to return maximum occurring character in the input string e.g., if input string is “test” then function should return ‘t’. 
Algorithm: One obvious approach to solve this problem would be to sort the input string and then traverse through the sorted string to find the character which is occurring maximum number of times. Let us see if we can improve on this. So we will use a technique called ‘Hashing’. In this, when we traverse through the string, we would hash each character into an array of ASCII characters.  
Input string = “test”
1: Construct character count array from the input string.
  count['e'] = 1
  count['s'] = 1
  count['t'] = 2

2: Return the index of maximum value in count array (returns ‘t’).
Typically, ASCII characters are 256, so we use our Hash array size as 256. But if we know that our input string will have characters with value from 0 to 127 only, we can limit Hash array size as 128. Similarly, based on extra info known about input string, the Hash array size can be limited to 26.Implementation: 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to output the maximum occurring character// in a string#include<bits/stdc++.h>#define ASCII_SIZE 256using namespace std; char getMaxOccurringChar(char* str){    // Create array to keep the count of individual    // characters and initialize the array as 0    int count[ASCII_SIZE] = {0};     // Construct character count array from the input    // string.    int len = strlen(str);    int max = 0;  // Initialize max count    char result;   // Initialize result     // Traversing through the string and maintaining    // the count of each character    for (int i = 0; i < len; i++) {        count[str[i]]++;        if (max < count[str[i]]) {            max = count[str[i]];            result = str[i];        }    }     return result;} // Driver program to test the above functionint main(){    char str[] = "sample string";    cout << "Max occurring character is "         << getMaxOccuringChar(str);}
// Java program to output the maximum occurring character// in a string public class GFG{    static final int ASCII_SIZE = 256;    static char getMaxOccurringChar(String str)    {        // Create array to keep the count of individual        // characters and initialize the array as 0        int count[] = new int[ASCII_SIZE];              // Construct character count array from the input        // string.        int len = str.length();        for (int i=0; i<len; i++)            count[str.charAt(i)]++;              int max = -1;  // Initialize max count        char result = ' ';   // Initialize result              // Traversing through the string and maintaining        // the count of each character        for (int i = 0; i < len; i++) {            if (max < count[str.charAt(i)]) {                max = count[str.charAt(i)];                result = str.charAt(i);            }        }              return result;    }         // Driver Method    public static void main(String[] args)    {        String str = "sample string";        System.out.println("Max occurring character is " +                            getMaxOccuringChar(str));    }}
# Python program to return the maximum occurring character in the input stringASCII_SIZE = 256 def getMaxOccurringChar(str):    # Create array to keep the count of individual characters    # Initialize the count array to zero    count = [0] * ASCII_SIZE     # Utility variables    max = -1    c = ''     # Traversing through the string and maintaining the count of    # each character    for i in str:        count[ord(i)]+=1;     for i in str:        if max < count[ord(i)]:            max = count[ord(i)]            c = i     return c # Driver program to test the above functionstr = "sample string"print("Max occurring character is",getMaxOccuringChar(str)) # Although this program can be written in atmost 3 lines in Python# the above program has been written for a better understanding of# the reader # Shorter version of the program# import collections# str = "sample string"# print "Max occurring character is " +#        collections.Counter(str).most_common(1)[0][0] # This code has been contributed by Bhavya Jain
// C# program to output the maximum// occurring character in a stringusing System; class GFG{    static int ASCII_SIZE = 256;         static char getMaxOccurringChar(String str)    {        // Create array to keep the count of        // individual characters and        // initialize the array as 0        int []count = new int[ASCII_SIZE];             // Construct character count array        // from the input string.        int len = str.Length;        for (int i = 0; i < len; i++)            count[str[i]]++;             int max = -1; // Initialize max count        char result = ' '; // Initialize result             // Traversing through the string and        // maintaining the count of each character        for (int i = 0; i < len; i++) {            if (max < count[str[i]]) {                max = count[str[i]];                result = str[i];            }        }             return result;    }         // Driver Method    public static void Main()    {        String str = "sample string";        Console.Write("Max occurring character is " +                            getMaxOccuringChar(str));    }} // This code is contributed by Sam007
<?php// PHP program to output the maximum// occurring character in a string$ASCII_SIZE = 256; function getMaxOccurringChar($str){    global $ASCII_SIZE;         // Create array to keep the count    // of individual characters and    // initialize the array as 0    $count = array_fill(0, $ASCII_SIZE, NULL);     // Construct character count array    // from the input string.    $len = strlen($str);    $max = 0; // Initialize max count     // Traversing through the string    // and maintaining the count of    // each character    for ($i = 0; $i < ($len); $i++)    {        $count[ord($str[$i])]++;        if ($max < $count[ord($str[$i])])        {            $max = $count[ord($str[$i])];            $result = $str[$i];        }    }     return $result;} // Driver Code$str = "sample string";echo "Max occurring character is " .           getMaxOccuringChar($str);             // This code is contributed by ita_c?>
<script>// Javascript program to output the maximum occurring character// in a string    let ASCII_SIZE = 256;    function getMaxOccurringChar(str)    {             // Create array to keep the count of individual        // characters and initialize the array as 0        let count = new Array(ASCII_SIZE);        for (let i = 0; i < ASCII_SIZE; i++)        {            count[i] = 0;        }                 // Construct character count array from the input        // string.        let len = str.length;        for (let i = 0; i < len; i++)        {            count[str[i].charCodeAt(0)] += 1;        }        let max = -1;   // Initialize max count        let result = ' ';   // Initialize result                 // Traversing through the string and maintaining        // the count of each character        for (let i = 0; i < len; i++)        {            if (max < count[str[i].charCodeAt(0)])            {                max = count[str[i].charCodeAt(0)];                result = str[i];            }        }        return result;    }         // Driver Method    let str = "sample string";    document.write("Max occurring character is " , getMaxOccuringChar(str));         // This code is contributed by avanitrachhadiya2155</script>
Output:  
Max occurring character is s
Time Complexity: O(n) Space Complexity: O(1) — Because we are using fixed space (Hash array) irrespective of input string size.Notes: If more than one characters have the same count and that count is maximum then the function returns the first character with maximum count in input string. For example if input string is “test sample” then there are three characters with same and maximum count two i.e. “t”, “e” and “s” but our program will result “t” because “t” comes first in input string. Similarly, the output for “cbbbbccc” would be “c”.As an variation to the above program, think about the change in code if you want to output “e” for input “test sample” i.e. the character of maximum count and that character should be of least ASCII value. For “cbbbbccc”, output should be “b”. Try it out !Also, can you think of improvement if we can avoid two loopings in the above? Basically, you need to figure out if we can solve the same problem with one loop itself instead of two loops.  
YouTubeGeeksforGeeks507K subscribersReturn maximum occurring character in an input string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:08•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=uwbBxoCrbMg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
Rajesh1978
ukasp
shubham_singh
avanitrachhadiya2155
amartyaghoshgfg
simmytarika5
Morgan Stanley
Hash
Strings
Morgan Stanley
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Most frequent element in an array
Sorting a Map by value in C++ STL
Double Hashing
Longest Consecutive Subsequence
C++ program for hashing with chaining
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4