Maximum count of substrings of length K consisting of same characters in C++

C++Server Side ProgrammingProgramming

Given the task is to find the maximum count of substrings of length K consisting of same characters. Given a string s and another integer K, we have to count the occurrence of sub-strings of size K that have same characters.

Out of the sub-strings that are found, we have to choose the sub-string occurring the maximum number of time.

Let’s now understand what we have to do using an example −


s = ”tuuxyyuuc”, K = 2




Here the sub-strings of length 2 and having same characters are: “uu” and “yy” but as it is seen that “yy” occurs only 1 time and “uu” is present 2 times. Therefore the output becomes 2.


s = “hhigggff”, K = 3



Approach used in the below program as follows

  • In Max() function, initialize int ans = 0 to store final answer, size = str.size() to store size of string and declare char c to store the characters we need to check.

  • Loop from j = 0 till j < 26 and put c = ‘a’ + j as we will check for each character.

  • Initialize variable int CurrCh = 0 for storing the occurrence of sub-array containing the current character.

  • Loop from i = 0 till i <= size – K and check if (str[i] != c). If so, then add continue; statement.

  • Initialize count = 0 to store length of the sub-array of the current character.

  • Create a while loop with condition (i < size && count != K && str[i] == c) and inside the loop increment i and count. Outside the while loop decrease i by 1.

  • Check if (count == K). If so, then increment CurrCh.

  • Close the second For loop and update the value of ans by putting ans = max(ans, CurrCh).

  • Finally close the first For loop and return ans.


 Live Demo

#include <bits/stdc++.h>
using namespace std;
int Max(string str, int K){
   int ans = 0, size = str.size();
   char c;
   //Checking for all characters
   for (int j = 0; j < 26; j++){
      c = 'a' + j;
      //checking for current character
      int CurrCh = 0;
      for (int i = 0; i <= size - K; i++){
         if (str[i] != c)
         //Counting the size of sub-string
         int count = 0;
         while (i < size && count != K && str[i] == c){
         //Increment CurrCh if sub-string has length K
         if (count == K)
      //Update ans
      ans = max(ans, CurrCh);
   return ans;
//main function
int main(){
   string str = "tuuuxyuuu";
   int K = 3;
   cout << Max(str, K);
   return 0;


Published on 04-Aug-2020 16:01:52