Swap For Longest Repeated Character Substring
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
text = "bbabbbcb"
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.
text = "aaabaaa"
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.
text = "aaaaa"
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)
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.