Find maximum occurring character in a string
Last Updated :
11 Mar, 2025
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
OutputMax 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();
OutputCharacter: e, Count: 4
Time Complexity: O(N), Traversing the string of length N one time.
Auxiliary Space: O(1)
Similar Reads
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 is
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 in
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 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'Ex
9 min read
First non-repeating character in a stream Given an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc
15+ min read
Count occurrences of a character in a repeated string Given an integer N and a lowercase string. The string is repeated infinitely. The task is to find the No. of occurrences of a given character x in first N letters.Examples: Input : N = 10 str = "abcac"Output : 4Explanation: "abcacabcac" is the substring from the infinitely repeated string. In first
8 min read