Repetitions
Find the longest contiguous block of equal characters in the given string.
Problem Summary
Original task summary for this archive page. The official CSES statement is linked in the header instead of being mirrored here.
Given one string, find the maximum length of a contiguous segment where every character is the same.
Editorial
The solution write-up is rendered from the LaTeX source, with equations kept live through MathJax.
Only adjacent equal characters matter, so a left-to-right scan is enough.
Maintain two values:
the length of the current run of equal characters
the best run length seen so far
When the current character matches the previous one, extend the current run. Otherwise start a new run of length \(1\). After each step, update the best answer.
This avoids any need for frequency maps because the problem is about consecutive characters, not total counts.
Complexity Analysis
Time and memory costs for the approach used in the implementation below.
Time: \(O(n)\)
Memory: \(O(1)\)
C++ Solution
The exact repository source used for this solution page.
#include <algorithm>
#include <iostream>
#include <string>
int main() {
std::string s;
std::cin >> s;
int best = 1;
int current = 1;
for (int i = 1; i < static_cast<int>(s.size()); ++i) {
if (s[i] == s[i - 1]) {
++current;
} else {
current = 1;
}
best = std::max(best, current);
}
std::cout << best << '\n';
return 0;
}
Notes / Pitfalls
Short reminders about edge cases, construction details, or common mistakes.
Remember to handle the first character cleanly. Initializing both the current run and the answer to \(1\) works for every non-empty string.
Source Files and Assets
Raw files are still available here when you want the original TeX, C++, or statement assets.