Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 the sliding window algorithm, where a stable window contains consecutive identical letters and one that contains different elements is unstable. The window adjusts by moving the start pointer when different characters are encountered.
Using Sliding Window Algorithm
The sliding window approach uses two pointers to track the current sequence of identical characters:
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;
}
end++;
} else {
start = end;
}
}
return max;
};
console.log(findMaximumRepeating(a));
Output
11
Alternative Method: Single Loop
Here's another approach using a single loop to count consecutive characters:
const findMaxRepeating = str => {
if (!str) return 0;
let maxCount = 1;
let currentCount = 1;
for (let i = 1; i < str.length; i++) {
if (str[i] === str[i - 1]) {
currentCount++;
maxCount = Math.max(maxCount, currentCount);
} else {
currentCount = 1;
}
}
return maxCount;
};
console.log(findMaxRepeating("fdsfjngjkdsfhhhhhhhhhhhfsdfsd"));
console.log(findMaxRepeating("aaabbbbcccc"));
console.log(findMaxRepeating("abcdef"));
11 4 1
How It Works
The sliding window algorithm works by:
- Maintaining two pointers:
startandend - Expanding the window when characters match
- Moving the start pointer to the current end position when characters differ
- Tracking the maximum window size encountered
Conclusion
Both methods efficiently find the maximum consecutive character count with O(n) time complexity. The sliding window approach is more versatile for similar problems, while the single loop method is simpler to understand.
