Longest substring without three repeats in a row
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Microsoft. It tests strings, sliding window and two pointers.
Given a string s, return the length of the longest substring of s in which no character appears three or more times in a row. Call such a substring semi-alternating: runs of one or two equal characters are fine, but a run of three is not.
Implement:
def longest_semi_alternating(s: str) -> int
A substring is a contiguous slice of s. Return 0 for the empty string.
Constraints
0 <= len(s) <= 2 * 10^5-
smay contain any characters (letters, digits, symbols), not only two letters. - Aim for O(n) time and O(1) extra space.
Example 1
s = "kkkhhkkkhh"
output: 6
The triple kkk appears twice. The longest stretch that avoids both is "kkhhkk" (indices 1 to 6).
Example 2
s = "ppqqpp"
output: 6
Every run has length at most two, so the whole string counts.
Interviewers often follow up by asking for the substring itself, a general limit of k repeats, or the number of valid substrings.
Clarifying questions
- Are equal characters compared exactly, so
"a"and"A"differ? - For a string shorter than three characters, is the answer its whole length?
- Do we need only the length, or also where the substring starts?
- Should a string of one repeated character, such as
"aaaa", give2?
What a strong answer covers
- Uses one sliding window. When
s[i] == s[i - 1] == s[i - 2], the window must restart ati - 1, because any valid substring ending atican hold at most the last two of the triple. - Updates the best length at every index. That is O(n) time and O(1) memory.
- Explains why the restart point is
i - 1and noti. - Tests the empty string, length 1 and 2,
"aaaa", a triple at the very start and end, and both examples.
Follow-ups
- Return the substring itself.
- A general limit: no character
kor more times in a row. - Count the valid substrings instead.
- Find the fewest deletions that make the whole string valid.
Where it's asked
What it tests
strings · sliding window · two pointers
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
