Introductory Problems
CSES • Introductory Problems

Repetitions

Find the longest contiguous block of equal characters in the given string.

Official statement
Updated May 21, 2026
Archive CSES Problem Set
Category Introductory Problems
Level basic
Status Solved
stringsscan

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.

C++

C++17 solution used on this page, with a copy button that targets the real source file contents.

Raw file
#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.

Show raw files