Skip to content
MediumSliding WindowAI interview only

Swap For Longest Repeated Character Substring

Asked atgoogleamazonmicrosoftbloomberg

01 · Problem

You are given a string text of lowercase English letters. You may pick any two positions and swap the characters at those positions at most once (you may also choose not to swap at all).

Return the length of the longest substring that consists of a single repeated character after performing at most one such swap.

A single character on its own counts as a run of length 1, so the answer is always at least 1.

02 · Examples

Example 01
Input
text = "bbabbbcb"
Output
6

Swap the 'a' at index 2 with the 'b' at index 7 to get "bbbbbbca", whose first six characters are all 'b'. There are only six 'b's, so 6 is the best possible.

Example 02
Input
text = "aaabaaa"
Output
6

Swap the 'b' with one of the outer 'a's, e.g. "aaaaaab", giving a run of six 'a's. Only six 'a's exist, so 7 is impossible.

Example 03
Input
text = "aaaaa"
Output
5

The whole string is already one run of 'a'; no swap is needed.

03 · Constraints

  • 011 <= text.length <= 2 * 104
  • 02text consists only of lowercase English letters
  • 03At most one swap of two characters is allowed; swapping is optional

04 · Optimal complexity

Time
O(n)
Space
O(1)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.