How to get the maximum count of repeated letters in a string? JavaScript

We have a string that contains some repeated letters like this −

const a = "fdsfjngjkdsfhhhhhhhhhhhfsdfsd";

Our job is to write a function that returns the count of maximum consecutive same letters in a streak. Like in the above string the letter h appears for 11 times in a row consecutively, so our function should return 11 for this string.

This problem is a good candidate for this sliding window algorithm, here a stable window will be the one that contains consecutive letters and one that contains different elements is unstable. The window tends to get stable by adding new letters at the end and removing repetitive letters at the start.

The code for this function that uses sliding window algorithm will be −


const a = "fdsfjngjkdsfhhhhhhhhhhhfsdfsd";
const findMaximumRepeating = str => {
   let max = 0;
   for(let start = 0, end = 1; end < str.length; ){
      if(str[end] === str[start]){
         if(max < end - start + 1){
            max = end - start + 1;
      } else {
         start = end;
   return max;


The output in the console will be −


Updated on: 28-Aug-2020


Kickstart Your Career

Get certified by completing the course

Get Started