Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count Occurrences of a Given Character in a String
Next article icon

Find maximum occurring character in a string

Last Updated : 11 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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

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 
Python
# 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
from collections import defaultdict  def find_max_character_count(s):     count_map = defaultdict(int)      # Count occurrences of each character     for ch in s:         count_map[ch] += 1      # Find the character with the maximum count     max_char = ''     max_count = 0      for char, count in count_map.items():         if count > max_count:             max_char = char             max_count = count      return {max_char: max_count}  # Main function to test if __name__ == "__main__":     string = "geeksforgeeks"      # Call the function and print the result     result = find_max_character_count(string)     for char, count in result.items():         # Using .format() for string formatting compatibility with older Python versions         print("Character: {}, Count: {}".format(char, count)) 
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
Character: e, Count: 4 

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



Next Article
Count Occurrences of a Given Character in a String
author
kartik
Improve
Article Tags :
  • DSA
  • Hash
  • Strings
  • Morgan Stanley
Practice Tags :
  • Morgan Stanley
  • Hash
  • Strings

Similar Reads

  • Maximum occurring lexicographically smallest character in a String
    Given a string containing lowercase characters. The task is to print the maximum occurring character in the input string. If 2 or more characters appear the same number of times, print the lexicographically (alphabetically) lowest (first) character. Examples: Input: test sample Output: e Explanation
    6 min read
  • Find one extra character in a string
    Given two strings which are of lengths n and n+1. The second string contains all the characters of the first string, but there is one extra character. Your task is to find the extra character in the second string. Examples: Input : string strA = "abcd"; string strB = "cbdae"; Output : e string B con
    15+ min read
  • Find the Nth occurrence of a character in the given String
    Given string str, a character ch, and a value N, the task is to find the index of the Nth occurrence of the given character in the given string. Print -1 if no such occurrence exists. Examples: Input: str = "Geeks", ch = 'e', N = 2 Output: 2 Input: str = "GFG", ch = 'e', N = 2 Output: -1 Recommended
    7 min read
  • Find Minimum Indexed Character in String
    Given a string str and another string patt. The task is to find the character in patt that is present at the minimum index in str. If no character of patt is present in str then print "$". Examples: Input: str = "geeksforgeeks", patt = "set" Output: e Both e and s of patt are present in str, but e i
    14 min read
  • Count Occurrences of a Given Character in a String
    Given a string S and a character 'c', the task is to count the occurrence of the given character in the string. Examples: Input : S = "geeksforgeeks" and c = 'e'Output : 4Explanation: 'e' appears four times in str. Input : S = "abccdefgaa" and c = 'a' Output : 3Explanation: 'a' appears three times i
    6 min read
  • Find last index of a character in a string
    Given a string str and a character x, find last index of x in str. Examples : Input : str = "geeks", x = 'e' Output : 2 Last index of 'e' in "geeks" is: 2 Input : str = "Hello world!", x = 'o' Output : 7 Last index of 'o' is: 7 Recommended PracticeLast index of a character in the stringTry It! Metho
    8 min read
  • Find the last non repeating character in string
    Given a string str, the task is to find the last non-repeating character in it. For example, if the input string is "GeeksForGeeks", then the output should be 'r' and if the input string is "GeeksQuiz" then the output should be 'z'. if there is no non-repeating character then print -1.Examples: Inpu
    5 min read
  • Find repeated character present first in a string
    Given a string, find the repeated character present first in the string.(Not the first repeated character, found here.) Examples: Input : geeksforgeeks Output : g (mind that it will be g, not e.) Asked in: Goldman Sachs internship Simple Solution using O(N^2) complexity: The solution is to loop thro
    15 min read
  • Searching For Characters and Substring in a String in Java
    Efficient String manipulation is very important in Java programming especially when working with text-based data. In this article, we will explore essential methods like indexOf(), contains(), and startsWith() to search characters and substrings within strings in Java. Searching for a Character in a
    5 min read
  • First non-repeating character of given string
    Given a string s of lowercase English letters, the task is to find the first non-repeating character. If there is no such character, return '$'. Examples: Input: s = "geeksforgeeks"Output: 'f'Explanation: 'f' is the first character in the string which does not repeat. Input: s = "racecar"Output: 'e'
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences