Open In App

Find maximum occurring character in a string

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

Given string str. The task is to find the maximum occurring character in the string str.

Examples:

Input: geeksforgeeks
Output: e
Explanation: ‘e’ occurs 4 times in the string

Input: test
Output: t
Explanation: ‘t’ occurs 2 times in the string

Recommended Practice

Return the maximum occurring character in an input string using Hashing:

Naive approach : ( using unordered_map ) 

In this approach we simply use the unordered_map from STL to store the frequency of every character and while adding characters to map we take a variable count to determine the element having highest frequency.

Implementation :

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
 
using namespace std;
 
// function that return maximum occurring character
char getMaxOccurringChar(string str)
{  
    // create unordered_map to store frequency of every character
    unordered_map<char,int>mp;
     
    // to store length of string
    int n = str.length();
     
    // to store answer
    char ans;
     
    // to check count of answer character is less or greater
    // than another elements count
    int cnt=0;
     
    // traverse the string
    for(int i=0 ;i<n ; i++){
        // push element into map and increase its frequency
        mp[str[i]]++;
         
        // update answer and count
        if(cnt < mp[str[i]]){
            ans = str[i];
            cnt = mp[str[i]];
        }
    }
     
    return ans;
     
}
 
// Driver Code
int main()
{
    string str = "sample string";
    cout << "Max occurring character is: "
         << getMaxOccurringChar(str);
}
 
// this code is contributed by bhardwajji


C




#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
// Function to find the maximum occurring character
char getMaxOccurringChar(char str[])
{
    // Create a hash table (unordered_map) to store the
    // frequency of each character
    int count[256] = { 0 };
 
    // Traverse the string and update the frequency of each
    // character
    int length = strlen(str);
    for (int i = 0; i < length; i++)
        count[(int)str[i]]++;
 
    // Find the character with the maximum frequency
    char maxChar;
    int maxCount = 0;
    for (int i = 0; i < length; i++) {
        if (count[(int)str[i]] > maxCount) {
            maxCount = count[(int)str[i]];
            maxChar = str[i];
        }
    }
 
    return maxChar;
}
 
// Driver Code
int main()
{
    char str[] = "sample string";
    printf("Max occurring character is: %c\n",
           getMaxOccurringChar(str));
    return 0;
}


Java




import java.util.*;
 
public class Main {
     
    // function that returns maximum occurring character
    static char getMaxOccurringChar(String str) {
         
        // create HashMap to store frequency of every character
        HashMap<Character, Integer> mp = new HashMap<>();
         
        // to store length of string
        int n = str.length();
         
        // to store answer
        char ans = 0;
         
        // to check count of answer character is less or greater
        // than another elements count
        int cnt = 0;
         
        // traverse the string
        for(int i = 0; i < n; i++) {
             
            // push element into map and increase its frequency
            char c = str.charAt(i);
            mp.put(c, mp.getOrDefault(c, 0) + 1);
             
            // update answer and count
            if(cnt < mp.get(c)) {
                ans = c;
                cnt = mp.get(c);
            }
        }
         
        return ans;
    }
 
    // Driver Code
    public static void main(String[] args) {
        String str = "sample string";
        System.out.println("Max occurring character is: " + getMaxOccurringChar(str));
    }
}
 
// This code is contributed by kalyanbef


Python3




# function that return maximum occurring character
def getMaxOccurringChar(str):
    # create dictionary to store frequency of every character
    mp = {}
 
    # to store length of string
    n = len(str)
 
    # to store answer
    ans = ''
 
    # to check count of answer character is less or greater
    # than another elements count
    cnt = 0
 
    # traverse the string
    for i in range(n):
        # push element into dictionary and increase its frequency
        if str[i] in mp:
            mp[str[i]] += 1
        else:
            mp[str[i]] = 1
 
        # update answer and count
        if cnt < mp[str[i]]:
            ans = str[i]
            cnt = mp[str[i]]
 
    return ans
 
 
# Driver Code
str = "sample string"
print("Max occurring character is:", getMaxOccurringChar(str))


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
 
class MainClass {
    public static void Main(string[] args)
    {
        string str = "sample string";
        Console.WriteLine("Max occurring character is: "
                          + getMaxOccurringChar(str));
    }
 
    // function that return maximum occurring character
    static char getMaxOccurringChar(string str)
    {
        // create dictionary to store frequency of every
        // character
        Dictionary<char, int> mp
            = new Dictionary<char, int>();
 
        // to store length of string
        int n = str.Length;
 
        // to store answer
        char ans = '\0';
 
        // to check count of answer character is less or
        // greater than another elements count
        int cnt = 0;
 
        // traverse the string
        for (int i = 0; i < n; i++) {
            // push element into map and increase its
            // frequency
            if (mp.ContainsKey(str[i])) {
                mp[str[i]]++;
            }
            else {
                mp.Add(str[i], 1);
            }
 
            // update answer and count
            if (cnt < mp[str[i]]) {
                ans = str[i];
                cnt = mp[str[i]];
            }
        }
 
        return ans;
    }
}


Javascript




// JavaScript program for the above approach
 
// function that return maximum occurring character
function getMaxOccurringChar(str)
{
 
    // create map to store frequency of every character
    let mp = new Map();
     
    // to store length of string
    let n = str.length;
     
    // to store answer
    let ans;
     
    // to check count of answer character is less or greater
    // than another elements count
    let cnt=0;
     
    // traverse the string
    for(let i=0 ;i<n ; i++){
        // push element into map and increase its frequency
        mp.set(str[i], (mp.get(str[i]) || 0) + 1);
         
        // update answer and count
        if(cnt < mp.get(str[i])){
            ans = str[i];
            cnt = mp.get(str[i]);
        }
    }
     
    return ans;
}
 
// Driver Code
let str = "sample string";
console.log("Max occurring character is: " + getMaxOccurringChar(str));
 
// This code is contributed by rutikbhosale


Output

Max occurring character is: s





Time Complexity: O(N), Traversing the string of length N one time.
Auxiliary Space: O(N), where N is the size of the string

The idea is to store the frequency of every character in the array and return the character with maximum count.

Follow the steps to solve the problem:

  • Create a count array of size 256 to store the frequency of every character of the string
  • Maintain a max variable to store the maximum frequency so far whenever encounter a frequency more than the max then update the max
  • And update that character in our result variable.

Below is the implementation of the above approach:

C++




#include <iostream>
#include <unordered_map>
#include <algorithm>
 
std::unordered_map<char, int> findMaxCharacterCount(const std::string& str) {
    std::unordered_map<char, int> countMap;
 
    // Count occurrences of each character
    for (char ch : str) {
        countMap[ch]++;
    }
 
    // Find the character with the maximum count
    char maxChar = '\0';
    int maxCount = 0;
 
    for (const auto& entry : countMap) {
        if (entry.second > maxCount) {
            maxChar = entry.first;
            maxCount = entry.second;
        }
    }
 
    std::unordered_map<char, int> result;
    result[maxChar] = maxCount;
    return result;
}
 
int main() {
    std::string str = "geeksforgeeks";
 
    // Call the function and print the result
    std::unordered_map<char, int> result = findMaxCharacterCount(str);
    std::cout << "Character: " << result.begin()->first << ", Count: " << result.begin()->second << std::endl;
 
    return 0;
}


Java




import java.util.HashMap;
import java.util.Map;
 
public class Main {
 
    public static Map<Character, Integer> findMaxCharacterCount(String str) {
        // Initialize max with the first character and its count
        Map<Character, Integer> max = new HashMap<>();
        max.put(str.charAt(0), str.length() - str.replace(String.valueOf(str.charAt(0)), "").length());
 
        // Iterate through the string to find the character with the maximum count
        for (char i : str.toCharArray()) {
            int count = str.length() - str.replace(String.valueOf(i), "").length();
            if (count > max.get(max.keySet().iterator().next())) {
                // Update max if the count is higher
                max.clear();
                max.put(i, count);
            }
        }
 
        return max;
    }
 
    public static void main(String[] args) {
        String str = "geeksforgeeks";
         
        // Call the function and print the result
        Map<Character, Integer> result = findMaxCharacterCount(str);
        System.out.println("Character: " + result.keySet().iterator().next() + ", Count: " + result.get(result.keySet().iterator().next()));
    }
}


Python




def func(str):
    max=[str[0],str.count(str[0])]
    for i in str:
        if str.count(i)>max[1]:
            max[0]=i
            max[1]=str.count(i)
 
    return(max)          
 
str="geeksforgeeks"
print(func(str))


C#




using System;
using System.Collections.Generic;
using System.Linq;
 
class Program
{
    static Dictionary<char, int> FindMaxCharacterCount(string str)
    {
        Dictionary<char, int> countMap = new Dictionary<char, int>();
 
        // Count occurrences of each character
        foreach (char ch in str)
        {
            if (countMap.ContainsKey(ch))
            {
                countMap[ch]++;
            }
            else
            {
                countMap[ch] = 1;
            }
        }
 
        // Find the character with the maximum count
        char maxChar = '\0';
        int maxCount = 0;
 
        foreach (var entry in countMap)
        {
            if (entry.Value > maxCount)
            {
                maxChar = entry.Key;
                maxCount = entry.Value;
            }
        }
 
        Dictionary<char, int> result = new Dictionary<char, int>();
        result[maxChar] = maxCount;
        return result;
    }
 
    static void Main(string[] args)
    {
        string str = "geeksforgeeks";
 
        // Call the function and print the result
        Dictionary<char, int> result = FindMaxCharacterCount(str);
        Console.WriteLine($"Character: {result.First().Key}, Count: {result.First().Value}");
    }
}


Javascript




// Function to find the character with the maximum count in a string
function findMaxCharacterCount(str) {
    let countMap = {};
 
    // Count occurrences of each character
    for (let ch of str) {
        if (countMap[ch])
            countMap[ch]++;
        else
            countMap[ch] = 1;
    }
 
    // Find the character with the maximum count
    let maxChar = '';
    let maxCount = 0;
 
    for (let [char, count] of Object.entries(countMap)) {
        if (count > maxCount) {
            maxChar = char;
            maxCount = count;
        }
    }
 
    let result = {};
    result[maxChar] = maxCount;
    return result;
}
 
// Main function
function main() {
    let str = "geeksforgeeks";
 
    // Call the function and print the result
    let result = findMaxCharacterCount(str);
    let maxEntry = Object.entries(result)[0];
    console.log(`Character: ${maxEntry[0]}, Count: ${maxEntry[1]}`);
}
 
// Invoke main function
main();


Output

Max occurring character is s





Time Complexity: O(N), Traversing the string of length N one time.
Auxiliary Space: O(1)



Last Updated : 20 Feb, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads