Longest substring without three repeats in a row
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.
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. Free with an account: one full answer per company.
