Swap For Longest Repeated Character Substring
MediumStringssliding window
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given a lowercase string text, you may swap the characters at two positions at most once (or not swap at all).
Return the length of the longest substring made of one repeated character that you can obtain.
Examples
Input: text = "ababa"
Output: 3
Swap the `b` at index 1 with the `a` at index 4 to get `"aaabb"`, which starts with `"aaa"`. Only three `a`s exist, so 3 is the maximum.
Input: text = "aaabaaa"
Output: 6
Swap the `b` at index 3 with the last `a` to get `"aaaaaab"`, which has six `a`s in a row. A seventh is impossible because the `b` must go somewhere.
Input: text = "aaaaa"
Output: 5
The string is already one run of five `a`s.
Constraints
- 1 <= text.length <= 2 * 10^4
- text consists of lowercase English letters
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.