Skip to main content

Maximum Occurring Character

Problem​

Given a string str of lowercase alphabets. The task is to find the maximum occurring character in the string str. If more than one character occurs the maximum number of time then print the lexicographically smaller character.

Examples:​

Example 1:

Input:
str = testsample
Output: e
Explanation: e is the character which is having the highest frequency.

Example 2:

Input:
str = output
Output: t
Explanation: t and u are the characters with the same frequency, but t is lexicographically smaller.

Your task:​

The task is to complete the function getMaxOccuringChar() which returns the character which is most occurring.

  • Expected Time Complexity: O(N)O(N)
  • Expected Auxiliary Space: OO(Number of distinct characters)

Note: N = |s|

Constraints:​

  • 1β‰€βˆ£sβˆ£β‰€1001 ≀ |s| ≀ 100

Solution​

Python​

def getMaxOccurringChar(self,s):
mp = {}
n = len(s)
ans = ''
cnt = 0

for i in range(n):
if s[i] in mp:
mp[s[i]] += 1
else:
mp[s[i]] = 1
if mp[s[i]] > cnt or (mp[s[i]] == cnt and s[i] < ans):
ans = s[i]
cnt = mp[s[i]]
return ans

Java​

public static char getMaxOccuringChar(String line) {
Map<Character, Integer> mp = new HashMap<>();
int n = line.length();
char ans = '\0';
int cnt = 0;
for (int i = 0; i < n; i++) {
char ch = line.charAt(i);
mp.put(ch, mp.getOrDefault(ch, 0) + 1);
if (mp.get(ch) > cnt || (mp.get(ch) == cnt && ch < ans)) {
ans = ch;
cnt = mp.get(ch);
}
}
return ans;
}

C++​

char getMaxOccuringChar(string str) {
unordered_map<char, int> mp;
char ans = '\0';
int cnt = 0;
for (char ch : str) {
mp[ch]++;
if (mp[ch] > cnt || (mp[ch] == cnt && ch < ans)) {
ans = ch;
cnt = mp[ch];
}
}
return ans;
}

C​

char getMaxOccuringChar(const char* str) {
int freq[256] = {0};
char ans = '\0';
int cnt = 0;
for (int i = 0; str[i] != '\0'; i++) {
freq[(int)str[i]]++;
if (freq[(int)str[i]] > cnt || (freq[(int)str[i]] == cnt && str[i] < ans)) {
ans = str[i];
cnt = freq[(int)str[i]];
}
}
return ans;
}
  • Time Complexity: O(N)O(N)
  • Auxiliary Space: OO(Number of distinct characters)