Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • 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
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
Maximum consecutive repeating character in string
Next article icon

Maximum consecutive repeating character in string

Last Updated : 18 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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: e
Explanation: character e comes 3 times consecutively which is maximum.

Input: s = "aaaabbcbbb"
Output: a
Explanation: character a comes 4 times consecutively which is maximum.

Table of Content

  • [Naive Approach] Using Nested Loop
  • [Expected Approach 1] Optimised Nested Loops
  • [Expected Approach 2] Using Counter Variable

[Naive Approach] Using Nested Loop

The idea is to use a nested loop approach where the outer loop iterates through each character of the string, and for each character, the inner loop counts the consecutive occurrences of that character by moving forward until a different character is encountered.

C++
// C++ program to find the maximum consecutive // repeating character in given string #include<iostream> using namespace std;  // function to find out the maximum repeating // character in given string char maxRepeating(string s) {     int n = s.length();     int maxCnt = 0;     char res = s[0];          // Find the maximum repeating character     // starting from s[i]     for (int i=0; i<n; i++) {         int cnt = 0;         for (int j=i; j<n; j++) {             if (s[i] != s[j])                 break;             cnt++;         }          // Update result if required         if (cnt > maxCnt) {             maxCnt = cnt;             res = s[i];         }     }          return res; }  int main() {      string s = "aaaabbaaccde";     cout << maxRepeating(s);     return 0; } 
Java
// Java program to find the maximum consecutive // repeating character in given string class GfG {      // Function to find out the maximum repeating     // character in given string     static char maxRepeating(String s) {         int n = s.length();         int maxCnt = 0;         char res = s.charAt(0);          // Find the maximum repeating character         // starting from s[i]         for (int i = 0; i < n; i++) {             int cnt = 0;             for (int j = i; j < n; j++) {                 if (s.charAt(i) != s.charAt(j))                     break;                 cnt++;             }              // Update result if required             if (cnt > maxCnt) {                 maxCnt = cnt;                 res = s.charAt(i);             }         }          return res;     }      public static void main(String[] args) {         String s = "aaaabbaaccde";         System.out.println(maxRepeating(s));     } } 
Python
# Python program to find the maximum consecutive # repeating character in given string  # Function to find out the maximum repeating # character in given string def maxRepeating(s):     n = len(s)     maxCnt = 0     res = s[0]      # Find the maximum repeating character     # starting from s[i]     for i in range(n):         cnt = 0         for j in range(i, n):             if s[i] != s[j]:                 break             cnt += 1          # Update result if required         if cnt > maxCnt:             maxCnt = cnt             res = s[i]      return res  if __name__ == "__main__":     s = "aaaabbaaccde"     print(maxRepeating(s)) 
C#
// C# program to find the maximum consecutive // repeating character in given string using System;  class GfG {      // Function to find out the maximum repeating     // character in given string     static char maxRepeating(string s) {         int n = s.Length;         int maxCnt = 0;         char res = s[0];          // Find the maximum repeating character         // starting from s[i]         for (int i = 0; i < n; i++) {             int cnt = 0;             for (int j = i; j < n; j++) {                 if (s[i] != s[j])                     break;                 cnt++;             }              // Update result if required             if (cnt > maxCnt) {                 maxCnt = cnt;                 res = s[i];             }         }          return res;     }      static void Main(string[] args) {         string s = "aaaabbaaccde";         Console.WriteLine(maxRepeating(s));     } } 
JavaScript
// JavaScript program to find the maximum consecutive // repeating character in given string  // Function to find out the maximum repeating // character in given string function maxRepeating(str) {     let n = s.length;     let maxCnt = 0;     let res = s[0];      // Find the maximum repeating character     // starting from s[i]     for (let i = 0; i < n; i++) {         let cnt = 0;         for (let j = i; j < n; j++) {             if (s[i] !== s[j])                 break;             cnt++;         }          // Update result if required         if (cnt > maxCnt) {             maxCnt = cnt;             res = s[i];         }     }      return res; }  //Driver Code let s = "aaaabbaaccde"; console.log(maxRepeating(s)); 

Output: 

a

Time Complexity : O(n^2), as we are using two nested loops.
Space Complexity : O(1)

[Expected Approach 1] Optimised Nested Loops

In the above approach, instead of running outer loop for each index from 0 to n -1, we can update it from the ending point of the inner loop, as we need not to count same elements multiple times, and can start the next iteration from the different element.

C++
// C++ program to find the maximum consecutive // repeating character in given string #include<iostream> using namespace std;  // function to find out the maximum repeating // character in given string char maxRepeating(string s) {     int n = s.length();     int maxCnt = 0;     char res = s[0];          // Find the maximum repeating character     // starting from s[i]     for (int i=0; i<n; i++) {         int cnt = 1;         while(i + 1 < n && s[i] == s[i + 1]) {             i++;             cnt++;         }          // Update result if required         if (cnt > maxCnt) {             maxCnt = cnt;             res = s[i];         }     }          return res; }  int main() {      string s = "aaaabbaaccde";     cout << maxRepeating(s);     return 0; } 
Java
// Java program to find the maximum consecutive // repeating character in given string class GFG {      // function to find out the maximum repeating     // character in given string     static char maxRepeating(String s) {         int n = s.length();         int maxCnt = 0;         char res = s.charAt(0);          // Find the maximum repeating character         // starting from s[i]         for (int i = 0; i < n; i++) {             int cnt = 1;             while (i + 1 < n && s.charAt(i) == s.charAt(i + 1)) {                 i++;                 cnt++;             }              // Update result if required             if (cnt > maxCnt) {                 maxCnt = cnt;                 res = s.charAt(i);             }         }          return res;     }      public static void main(String[] args) {         String s = "aaaabbaaccde";         System.out.println(maxRepeating(s));     } } 
Python
# Python program to find the maximum consecutive # repeating character in given string  # function to find out the maximum repeating # character in given string def maxRepeating(s):     n = len(s)     maxCnt = 0     res = s[0]      # Find the maximum repeating character     # starting from s[i]     i = 0     while i < n:         cnt = 1         while i + 1 < n and s[i] == s[i + 1]:             i += 1             cnt += 1          # Update result if required         if cnt > maxCnt:             maxCnt = cnt             res = s[i]          i += 1      return res  # Main function def main():     s = "aaaabbaaccde"     print(maxRepeating(s))  if __name__ == "__main__":     main() 
C#
// C# program to find the maximum consecutive // repeating character in given string using System;  class GFG {      // function to find out the maximum repeating     // character in given string     static char MaxRepeating(string s) {         int n = s.Length;         int maxCnt = 0;         char res = s[0];          // Find the maximum repeating character         // starting from s[i]         for (int i = 0; i < n; i++) {             int cnt = 1;             while (i + 1 < n && s[i] == s[i + 1]) {                 i++;                 cnt++;             }              // Update result if required             if (cnt > maxCnt) {                 maxCnt = cnt;                 res = s[i];             }         }          return res;     }      public static void Main() {         string s = "aaaabbaaccde";         Console.WriteLine(MaxRepeating(s));     } } 
JavaScript
// JavaScript program to find the maximum consecutive // repeating character in given string  // function to find out the maximum repeating // character in given string function maxRepeating(s) {     let n = s.length;     let maxCnt = 0;     let res = s[0];      // Find the maximum repeating character     // starting from s[i]     for (let i = 0; i < n; i++) {         let cnt = 1;         while (i + 1 < n && s[i] === s[i + 1]) {             i++;             cnt++;         }          // Update result if required         if (cnt > maxCnt) {             maxCnt = cnt;             res = s[i];         }     }      return res; }  // Main function function main() {     let s = "aaaabbaaccde";     console.log(maxRepeating(s)); }  // Run the main function main(); 

Output
a

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

[Expected Approach 2] Using Counter Variable

The idea is to traverse the string from the second character (index 1) and for each character, compare it with the previous character to identify consecutive repeating sequences. When the current character matches the previous one, we increment a counter, and when it differs, reset the counter to 1. Check if the current streak is longer than the maximum streak seen so far - if yes, we update both the maximum count and the result character.

C++
// C++ program to find the maximum consecutive // repeating character in given string #include <iostream> using namespace std;  // Function to find out the maximum repeating // character in given string char maxRepeating(string s) {     int n = s.length();     int maxCnt = 0;     char res = s[0];     int cnt = 1;      for (int i = 1; i < n; i++) {          // If current char matches with         // previous, increment cnt         if (s[i] == s[i - 1]) {             cnt++;         }         else {              // Reset cnt             cnt = 1;         }          // Update result if required         if (cnt > maxCnt) {             maxCnt = cnt;             res = s[i - 1];         }     }      return res; }  // Driver Code int main() {     string s = "aaaabbaaccde";     cout << maxRepeating(s) << endl;     return 0; } 
Java
// Java program to find the maximum consecutive // repeating character in given string class GFG {      // Function to find out the maximum repeating     // character in given string     static char maxRepeating(String s) {         int n = s.length();         int maxCnt = 0;         char res = s.charAt(0);         int cnt = 1;          for (int i = 1; i < n; i++) {              // If current char matches with             // previous, increment cnt             if (s.charAt(i) == s.charAt(i - 1)) {                 cnt++;             }              else {                  // Reset cnt                 cnt = 1;             }              // Update result if required             if (cnt > maxCnt) {                 maxCnt = cnt;                 res = s.charAt(i - 1);             }         }          return res;     }      // Driver Code     public static void main(String[] args) {         String s = "aaaabbaaccde";         System.out.println(maxRepeating(s));     } } 
Python
# Python program to find the maximum consecutive # repeating character in given string  # Function to find out the maximum repeating # character in given string def maxRepeating(s):     n = len(s)     maxCnt = 0     res = s[0]     cnt = 1      for i in range(1, n):          # If current char matches with         # previous, increment cnt         if s[i] == s[i - 1]:             cnt += 1         else:              # Reset cnt             cnt = 1          # Update result if required         if cnt > maxCnt:             maxCnt = cnt             res = s[i - 1]      return res  # Driver Code s = "aaaabbaaccde" print(maxRepeating(s)) 
C#
// C# program to find the maximum consecutive // repeating character in given string using System;  class GFG {      // Function to find out the maximum repeating     // character in given string     static char MaxRepeating(string s) {         int n = s.Length;         int maxCnt = 0;         char res = s[0];         int cnt = 1;          for (int i = 1; i < n; i++) {              // If current char matches with             // previous, increment cnt             if (s[i] == s[i - 1]) {                 cnt++;             }              else {                  // Reset cnt                 cnt = 1;             }              // Update result if required             if (cnt > maxCnt) {                 maxCnt = cnt;                 res = s[i - 1];             }         }          return res;     }      // Driver Code     public static void Main() {         string s = "aaaabbaaccde";         Console.WriteLine(MaxRepeating(s));     } } 
JavaScript
// JavaScript program to find the maximum consecutive // repeating character in given string  // Function to find out the maximum repeating // character in given string function maxRepeating(s) {     let n = s.length;     let maxCnt = 0;     let res = s[0];     let cnt = 1;      for (let i = 1; i < n; i++) {          // If current char matches with         // previous, increment cnt         if (s[i] === s[i - 1]) {             cnt++;         }         else {              // Reset cnt             cnt = 1;         }          // Update result if required         if (cnt > maxCnt) {             maxCnt = cnt;             res = s[i - 1];         }     }      return res; }  //Driver Code let s = "aaaabbaaccde"; console.log(maxRepeating(s)); 

Output
a

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


Next Article
Maximum consecutive repeating character in string

D

DANISH_RAZA
Improve
Article Tags :
  • Strings
  • DSA
  • Amazon
Practice Tags :
  • Amazon
  • Strings

Similar Reads

    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. Examples: I
    6 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 stringInput: testOutput: tExplanation: 't' occurs 2 times in the stringReturn the maximum occurring character in an input string using
    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
    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
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