Maximum repeating character for every index in given String
Given string str consisting of lowercase alphabets, the task is to find the maximum repeating character obtained for every character of the string. If for any index, more than one character has occurred a maximum number of times, then print the character which had occurred most recently.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: str = “abbc”
a -> 1
b -> 1
b -> 2
b -> 2
str = ‘a’. Therefore, print a -> 1.
str = ‘b’. Now ‘a’ and ‘b’ have equal frequency. Since, ‘b’ is the most recently occurring character, print b -> 1.
str = ‘b’. Since ‘b’is the most repeating character, print b -> 2.
str = ‘c’. Since ‘b’is the most repeating character, print b -> 2.
Input: str = “htdddg”
Output:h -> 1
t -> 1
d -> 1
d -> 2
d -> 3
d -> 3
Approach: Follow the steps given below to solve the problem:
- Initialize an array, say freq to store the frequency of each distinct character in the string.
- Initialize two variables, say max, charMax to store the frequency of maximum repeating character and the maximum repeating character respectively.
- Traverse the string and update the frequency of current character, update the value of max and charMax.
- Finally, print the value of charMax and max after every character traversal.
Below is the implementation of the above approach:
a -> 1 b -> 1 b -> 2 b -> 2
Time Complexity: O(N)
Auxiliary Space: O(1)