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:
Maximum consecutive repeating character in string
Next article icon

Maximum repeating character for every index in given String

Last Updated : 18 Jun, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Examples:

Input: str = “abbc”
Output: 
a -> 1
b -> 1
b -> 2
b -> 2 
Explanation: 
str[0] = ‘a’. Therefore, print a -> 1. 
str[1] = ‘b’. Now ‘a’ and ‘b’ have equal frequency. Since, ‘b’ is the most recently occurring character, print b -> 1. 
str[2] = ‘b’. Since ‘b’is the most repeating character, print b -> 2. 
str[3] = ‘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:

C++




// C++ Program to implement
// the above approach
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the
// maximum repeating
// character at each index
// of the String
void findFreq(string str,
              int N)
{
  // Stores frequency of
  // each distinct character
  int freq[256];
   
  memset(freq, 0,
         sizeof(freq));
 
  // Stores frequency of
  // maximum repeating
  // character
  int max = 0;
 
  // Stores the character having
  // maximum frequency
  char charMax = '0';
 
  // Traverse the String
  for (int i = 0; i < N; i++)
  {
    // Stores current character
    char ch = str[i];
 
    // Update the frequency of str[i]
    freq[ch]++;
 
    // If frequency of current
    // character exceeds max
    if (freq[ch] >= max)
    {
      // Update max
      max = freq[ch];
 
      // Update charMax
      charMax = ch;
    }
 
    // Print the required output
    cout<< charMax << "->" <<
           max << endl;
  }
}
 
// Driver Code
int main()
{
  string str = "abbc";
 
  // Stores length of str
  int N = str.size();
 
  findFreq(str, N);
}
 
// This code is contributed by Rajput-Ji
 
 

Java




// Java program to implement
// the above approach
 
import java.util.*;
 
public class GFG {
 
    // Function to print the maximum repeating
    // character at each index of the string
    public static void findFreq(String str,
                                int N)
    {
 
        // Stores frequency of
        // each distinct character
        int[] freq = new int[256];
 
        // Stores frequency of maximum
        // repeating character
        int max = 0;
 
        // Stores the character having
        // maximum frequency
        char charMax = '0';
 
        // Traverse the string
        for (int i = 0; i < N; i++) {
 
            // Stores current character
            char ch = str.charAt(i);
 
            // Update the frequency of str[i]
            freq[ch]++;
 
            // If frequency of current
            // character exceeds max
            if (freq[ch] >= max) {
 
                // Update max
                max = freq[ch];
 
                // Update charMax
                charMax = ch;
            }
 
            // Print the required output
            System.out.println(
                charMax + " -> " + max);
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        String str = "abbc";
 
        // Stores length of str
        int N = str.length();
 
        findFreq(str, N);
    }
}
 
 

Python3




# Python3 program to implement
# the above approach
 
# Function to print the maximum repeating
# character at each index of the string
def findFreq(strr, N):
     
    # Stores frequency of
    # each distinct character
    freq = [0] * 256
 
    # Stores frequency of maximum
    # repeating character
    max = 0
 
    # Stores the character having
    # maximum frequency
    charMax = '0'
 
    # Traverse the string
    for i in range(N):
         
        # Stores current character
        ch = ord(strr[i])
 
        # Update the frequency of strr[i]
        freq[ch] += 1
 
        # If frequency of current
        # character exceeds max
        if (freq[ch] >= max):
 
            # Update max
            max = freq[ch]
 
            # Update charMax
            charMax = ch
 
        # Print the required output
        print(chr(charMax), "->", max)
 
# Driver Code
if __name__ == '__main__':
     
    strr = "abbc"
 
    # Stores length of strr
    N = len(strr)
 
    findFreq(strr, N)
 
# This code is contributed by mohit kumar 29
 
 

C#




// C# program to implement
// the above approach
using System;
class GFG{
 
// Function to print the maximum repeating
// character at each index of the string
public static void findFreq(String str,
                            int N)
{
  // Stores frequency of
  // each distinct character
  int[] freq = new int[256];
 
  // Stores frequency of maximum
  // repeating character
  int max = 0;
 
  // Stores the character having
  // maximum frequency
  char charMax = '0';
 
  // Traverse the string
  for (int i = 0; i < N; i++)
  {
    // Stores current character
    char ch = str[i];
 
    // Update the frequency of
    // str[i]
    freq[ch]++;
 
    // If frequency of current
    // character exceeds max
    if (freq[ch] >= max)
    {
      // Update max
      max = freq[ch];
 
      // Update charMax
      charMax = ch;
    }
 
    // Print the required output
    Console.WriteLine(charMax +
                      " -> " + max);
  }
}
 
// Driver Code
public static void Main(String[] args)
{
  String str = "abbc";
 
  // Stores length of str
  int N = str.Length;
 
  findFreq(str, N);
}
}
 
// This code is contributed by shikhasingrajput
 
 

Javascript




<script>
 
// JavaScript Program to implement
// the above approach
 
// Function to print the
// maximum repeating
// character at each index
// of the String
function findFreq(str, N) {
    // Stores frequency of
    // each distinct character
    let freq = new Array(256).fill(0);
 
 
    // Stores frequency of
    // maximum repeating
    // character
    let max = 0;
 
    // Stores the character having
    // maximum frequency
    let charMax = '0';
 
    // Traverse the String
    for (let i = 0; i < N; i++) {
        // Stores current character
        let ch = str[i].charCodeAt(0);
 
        // Update the frequency of str[i]
        freq[ch]++;
 
        // If frequency of current
        // character exceeds max
        if (freq[ch] >= max) {
            // Update max
            max = freq[ch];
 
            // Update charMax
            charMax = ch;
        }
 
        // Print the required output
        document.write(String.fromCharCode(charMax) + "->" +
        max + "<br>");
    }
}
 
// Driver Code
 
let str = "abbc";
 
// Stores length of str
let N = str.length;
 
findFreq(str, N);
 
 
// This code is contributed by gfgking
 
</script>
 
 
Output: 
a -> 1 b -> 1 b -> 2 b -> 2

 

Time Complexity: O(N)
Auxiliary Space: O(1)



Next Article
Maximum consecutive repeating character in string

K

kunalsg18elec
Improve
Article Tags :
  • DSA
  • Hash
  • Strings
  • frequency-counting
  • strings
Practice Tags :
  • Hash
  • Strings
  • Strings

Similar Reads

  • Maximum consecutive repeating character in string
    Given a string s, the task is to find the maximum consecutive repeating character in the string. Note: We do not need to consider the overall count, but the count of repeating that appears in one place. Examples: Input: s = "geeekk"Output: eExplanation: character e comes 3 times consecutively which
    11 min read
  • Maximum repeated frequency of characters in a given string
    Given a string S, the task is to find the count of maximum repeated frequency of characters in the given string S.Examples: Input: S = "geeksgeeks" Output: Frequency 2 is repeated 3 times Explanation: Frequency of characters in the given string - {"g": 2, "e": 4, "k": 2, "s": 2} The frequency 2 is r
    6 min read
  • Find maximum occurring character in a string
    Given string str. The task is to find the maximum occurring character in the string str. Examples: Input: geeksforgeeksOutput: eExplanation: 'e' occurs 4 times in the string Input: testOutput: tExplanation: 't' occurs 2 times in the string Return the maximum occurring character in an input string us
    9 min read
  • Remove odd indexed characters from a given string
    Given string str of size N, the task is to remove the characters present at odd indices (0-based indexing) of a given string. Examples : Input: str = “abcdef”Output: aceExplanation:The characters 'b', 'd' and 'f' are present at odd indices, i.e. 1, 3 and 5 respectively. Therefore, they are removed f
    4 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
  • Largest index for each distinct character in given string with frequency K
    Given a string S consisting of lowercase English letters and an integer K, the task is to find, for each distinct character in S, the largest index having this character exactly K times. If no such characters exist, print -1. Print the result in a lexicographical ordering.Note: Consider 0-based inde
    8 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
  • Split string to get maximum common characters
    Given a string S of length, N. Split them into two strings such that the number of common characters between the two strings is maximized and return the maximum number of common characters. Examples: Input: N = 6, S = abccbaOutput: 3Explanation: Splitting two strings as "abc" and "cba" has at most 3
    6 min read
  • Index of character depending on frequency count in string
    Given a string str containing only lowercase characters, the task is to answer Q queries of the following type: 1 C X: Find the largest i such that str[0...i] has exactly X occurrence of the character C.2 C X: Find the smallest i such that str[0...i] has exactly X occurrence of the character C. Exam
    10 min read
  • Maximum moves to reach destination character in a cyclic String
    Given a cyclic string S of length N consisting of only three characters 'a', 'b', and 'c'. Also given two characters, initial character (ic) and final character (fc). the task is to find the maximum distance from ic to its closest fc. Examples: Input: s = "caacb", ic = 'c', fc = 'a'Output: 3Explanat
    6 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