VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-consecutive-repeating-character-string/

⇱ Maximum consecutive repeating character in string - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum consecutive repeating character in string

Last Updated : 18 Feb, 2025

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.

[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.

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.


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.


Output
a

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

Comment
Article Tags:
Article Tags: