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
Finding the character with longest consecutive repetitions in a string and its length using JavaScript
We need to write a JavaScript function that finds the character with the longest consecutive repetitions in a string and returns both the character and its count as an array.
Problem
Given a string, we want to identify which character appears the most times consecutively and return an array containing the character and its consecutive count.
Example
Here's a solution that tracks consecutive characters and finds the maximum:
const str = 'tdfdffddffsdsfffffsdsdsddddd';
const findConsecutiveCount = (str = '') => {
if (!str) return ['', 0];
let maxChar = str[0];
let maxCount = 1;
let currentCount = 1;
for (let i = 1; i maxCount) {
maxCount = currentCount;
maxChar = str[i-1];
}
currentCount = 1;
}
}
// Check the last sequence
if (currentCount > maxCount) {
maxCount = currentCount;
maxChar = str[str.length-1];
}
return [maxChar, maxCount];
};
console.log(findConsecutiveCount(str));
console.log(findConsecutiveCount('aabbbbcccc'));
console.log(findConsecutiveCount('abcdef'));
console.log(findConsecutiveCount(''));
['f', 5] ['b', 4] ['a', 1] ['', 0]
How It Works
The algorithm uses these key variables:
- maxChar: Stores the character with longest consecutive sequence
- maxCount: Stores the maximum consecutive count found
- currentCount: Tracks the current consecutive sequence length
The function iterates through the string, comparing each character with the previous one. When characters differ, it checks if the current sequence is longer than the maximum found so far.
Alternative Approach Using Regular Expressions
const findConsecutiveCountRegex = (str = '') => {
if (!str) return ['', 0];
let maxChar = '';
let maxCount = 0;
// Find all consecutive character sequences
const matches = str.match(/(.)\1*/g) || [];
matches.forEach(match => {
if (match.length > maxCount) {
maxCount = match.length;
maxChar = match[0];
}
});
return [maxChar, maxCount];
};
console.log(findConsecutiveCountRegex('tdfdffddffsdsfffffsdsdsddddd'));
console.log(findConsecutiveCountRegex('aaabbbccccc'));
['f', 5] ['c', 5]
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Loop-based | O(n) | O(1) | Good |
| Regex-based | O(n) | O(k) where k is number of sequences | Very Good |
Conclusion
Both approaches effectively find the character with longest consecutive repetitions. The loop-based method is more memory efficient, while the regex approach is more concise and readable for this specific pattern matching task.
