Find maximum occurring character in a string
Last Updated :
20 Feb, 2024
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++
#include <bits/stdc++.h>
using namespace std;
char getMaxOccurringChar(string str)
{
unordered_map< char , int >mp;
int n = str.length();
char ans;
int cnt=0;
for ( int i=0 ;i<n ; i++){
mp[str[i]]++;
if (cnt < mp[str[i]]){
ans = str[i];
cnt = mp[str[i]];
}
}
return ans;
}
int main()
{
string str = "sample string" ;
cout << "Max occurring character is: "
<< getMaxOccurringChar(str);
}
|
C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char getMaxOccurringChar( char str[])
{
int count[256] = { 0 };
int length = strlen (str);
for ( int i = 0; i < length; i++)
count[( int )str[i]]++;
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;
}
int main()
{
char str[] = "sample string" ;
printf ( "Max occurring character is: %c\n" ,
getMaxOccurringChar(str));
return 0;
}
|
Java
import java.util.*;
public class Main {
static char getMaxOccurringChar(String str) {
HashMap<Character, Integer> mp = new HashMap<>();
int n = str.length();
char ans = 0 ;
int cnt = 0 ;
for ( int i = 0 ; i < n; i++) {
char c = str.charAt(i);
mp.put(c, mp.getOrDefault(c, 0 ) + 1 );
if (cnt < mp.get(c)) {
ans = c;
cnt = mp.get(c);
}
}
return ans;
}
public static void main(String[] args) {
String str = "sample string" ;
System.out.println( "Max occurring character is: " + getMaxOccurringChar(str));
}
}
|
Python3
def getMaxOccurringChar( str ):
mp = {}
n = len ( str )
ans = ''
cnt = 0
for i in range (n):
if str [i] in mp:
mp[ str [i]] + = 1
else :
mp[ str [i]] = 1
if cnt < mp[ str [i]]:
ans = str [i]
cnt = mp[ str [i]]
return ans
str = "sample string"
print ( "Max occurring character is:" , getMaxOccurringChar( str ))
|
C#
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));
}
static char getMaxOccurringChar( string str)
{
Dictionary< char , int > mp
= new Dictionary< char , int >();
int n = str.Length;
char ans = '\0' ;
int cnt = 0;
for ( int i = 0; i < n; i++) {
if (mp.ContainsKey(str[i])) {
mp[str[i]]++;
}
else {
mp.Add(str[i], 1);
}
if (cnt < mp[str[i]]) {
ans = str[i];
cnt = mp[str[i]];
}
}
return ans;
}
}
|
Javascript
function getMaxOccurringChar(str)
{
let mp = new Map();
let n = str.length;
let ans;
let cnt=0;
for (let i=0 ;i<n ; i++){
mp.set(str[i], (mp.get(str[i]) || 0) + 1);
if (cnt < mp.get(str[i])){
ans = str[i];
cnt = mp.get(str[i]);
}
}
return ans;
}
let str = "sample string" ;
console.log( "Max occurring character is: " + getMaxOccurringChar(str));
|
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;
for ( char ch : str) {
countMap[ch]++;
}
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" ;
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) {
Map<Character, Integer> max = new HashMap<>();
max.put(str.charAt( 0 ), str.length() - str.replace(String.valueOf(str.charAt( 0 )), "" ).length());
for ( char i : str.toCharArray()) {
int count = str.length() - str.replace(String.valueOf(i), "" ).length();
if (count > max.get(max.keySet().iterator().next())) {
max.clear();
max.put(i, count);
}
}
return max;
}
public static void main(String[] args) {
String str = "geeksforgeeks" ;
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 >();
foreach ( char ch in str)
{
if (countMap.ContainsKey(ch))
{
countMap[ch]++;
}
else
{
countMap[ch] = 1;
}
}
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" ;
Dictionary< char , int > result = FindMaxCharacterCount(str);
Console.WriteLine($ "Character: {result.First().Key}, Count: {result.First().Value}" );
}
}
|
Javascript
function findMaxCharacterCount(str) {
let countMap = {};
for (let ch of str) {
if (countMap[ch])
countMap[ch]++;
else
countMap[ch] = 1;
}
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;
}
function main() {
let str = "geeksforgeeks" ;
let result = findMaxCharacterCount(str);
let maxEntry = Object.entries(result)[0];
console.log(`Character: ${maxEntry[0]}, Count: ${maxEntry[1]}`);
}
main();
|
Output
Max occurring character is s
Time Complexity: O(N), Traversing the string of length N one time.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...