Longest Run Using No More Than Two Letter Kinds
StringsAuto-graded · 24 test casesLast updated
Find the longest contiguous stretch of a string containing at most two different characters, testing the sliding window technique with a frequency map.
Longest Two-Character Stretch
You are given a string text. A stretch is any block of consecutive characters taken from text. Your task is to determine how long the longest stretch can be, given that it may contain no more than two different characters.
Rules
- Characters are compared exactly as they appear, so uppercase and lowercase letters are different characters (
'a'and'A'count as two kinds). - A stretch that uses only one kind of character is also allowed.
- If
textis empty, the answer is0.
Input
text: a string made up of printable ASCII characters.
Output
- An integer: the length of the longest stretch of
textthat contains at most two distinct characters.
Constraints
0 <= len(text) <= 10^5textcontains only printable ASCII characters.- The expected solution runs in linear time in
len(text).
Examples
Example 1
Input: longest_two_kind_stretch('eceba')
Output: 3
Example 2
Input: longest_two_kind_stretch('ccaabbb')
Output: 5
Example 3
Input: longest_two_kind_stretch('')
Output: 0
Example 4
Input: longest_two_kind_stretch('abababab')
Output: 8
Hints
Hint 1
If a stretch already has at most two distinct characters, any smaller stretch inside it is also valid. That suggests growing a window and only trimming it when it becomes invalid.
Hint 2
Keep two indices, a left and a right edge, plus a dictionary of how many times each character appears inside the window. Move the right edge one step at a time and add the new character.
Hint 3
When the dictionary holds more than two keys, advance the left edge, decrementing counts and deleting a key as soon as its count reaches zero. After restoring validity, record the window length.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Use a sliding window over text, defined by a left index and a right index, together with a dictionary that stores how many times each character occurs inside the window.
For each position right:
- Add
text[right]to the dictionary (increment its count). - While the dictionary has more than two keys, take the character at
left, decrement its count, delete the key if the count hits zero, and moveleftforward by one. - The window is now valid, so compare its length
right - left + 1with the best length seen so far.
Removing keys whose count is zero is important: it makes the dictionary size equal to the exact number of distinct characters in the window, so the validity check is a constant-time len call.
Why it works
Validity is monotone: if a block has at most two distinct characters, every block inside it does too. So for a fixed right end, the valid left ends form a contiguous range reaching up to right. The loop leaves left at the smallest valid start for the current right, because left only moves when the window is invalid, and any start it skipped was already invalid for an earlier right end, hence invalid for this one as well.
Therefore, for the optimal block ending at index j, when right = j the window starts at or before the optimal start, and the recorded length is at least the optimal length. Every recorded window is valid, so the result never exceeds the optimum. The answer is exact.
Edge cases follow naturally: an empty string never enters the loop and returns 0; strings of one or two distinct characters never shrink, so the answer is len(text).
Complexity
- Time: O(n). Each index is added once by
rightand removed at most once byleft. - Space: O(1), since the dictionary never holds more than three keys.
Reference solution
def longest_two_kind_stretch(text: str) -> int:
counts = {}
left = 0
best = 0
for right, ch in enumerate(text):
counts[ch] = counts.get(ch, 0) + 1
while len(counts) > 2:
old = text[left]
counts[old] -= 1
if counts[old] == 0:
del counts[old]
left += 1
best = max(best, right - left + 1)
return best