Sep 082012

Write a function which will print the character coming maximum number of times in a given String. For example:

Input String: ritambhara
Output: a

Because character ‘a‘ appears 3 times in the String.


    Create a Character Count Array 
    (Which will contain the number of times a particular character appears in the string)
    Ex: If input string is "ritambhra", then 
        cout['a'] = 3
        cout['b'] = 1
        cout['h'] = 1
        cout['i'] = 1
        cout['r'] = 2
        cout['t'] = 1
    the size of this array can be 256 for local English characters. 
    If there are characters of other locales also, then you can increase the size appropriately.
    Scan the Count array and print the character for which count is max.


    void printMaxOccuringChar(char* str)
        // Boundary check
        if(str == NULL || str[0] == '\0')
            printf("EMPTY STRING");

        // Count Array. All elements are zeros
        int cntArr[256] = {0};

        // Populating the Count Array
        for(int i = 0; str[i] != '\0';  i++)

        // Getting the index of Maximum count in the Array
        int maxCntIdx = 0;
        for(int i=0; i < 256; i++)
            if(cntArr[i] > cntArr[maxCntIdx])
                maxCntIdx = i;

        printf("Character '%c' Appears Maximum %d times in \"%s\"", maxCntIdx, cntArr[maxCntIdx], str);

Sample Run of the above code:


Another Code can be when we are keeping the track of maximum at the same when we are populating the count array:

char maxOccuringChar(char* str)
    if(str == NULL)
        return NULL;

    int count[256] = {0};
    int maxOccuringChar = str[0];

    for(int i=1; str[i]!='\0'; i++)

        if(count[maxOccuringChar] < count[str[i]])
            maxOccuringChar = str[i];

    return maxOccuringChar;

  One Response to “Print character occurring maximum number of times in a string”

Comments (1)
  1. I have a small doubt..that when u are using cntArr[] in the second for loop, u are using number as index…y u r not using character as index…i will glad if any one can clear my doubt/ 🙂

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>