Longest substring of unique characters
September 7, 2012
Add two integers without using arithmetic operator
September 8, 2012

Print character occurring maximum number of times in a string

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.

Algorithm:

Step-1:
    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.
Step-2:
    Scan the Count array and print the character for which count is max.

Code:

    void printMaxOccuringChar(char* str)
    {
        // Boundary check
        if(str == NULL || str[0] == '\0')
        {
            printf("EMPTY STRING");
            return;
        }
        // Count Array. All elements are zeros
        int cntArr[256] = {0};
        // Populating the Count Array
        for(int i = 0; str[i] != '\0';  i++)
            cntArr[str[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:

Method-2:
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];
    count[str[0]]++;
    for(int i=1; str[i]!='\0'; i++)
    {
        count[str[i]]++;
        if(count[maxOccuringChar] < count[str[i]])
            maxOccuringChar = str[i];
    }
    return maxOccuringChar;
}

3 Comments

  1. Priya Nandy says:

    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/ 🙂

  2. Isha Singh says:

    Can u explain all the programs without using scanner class

  3. Isha Singh says:

    Can u explain all the programs without using scanner class
    It will glad if u do so.

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *