You are given a string s. Write a function to find the longest substring that contains no more than two distinct characters. Please this is a sliding window problem, write a function that solves this problem, and explain your algorithm.
Assistant
We are given a string s, and we need to find the longest substring with at most two distinct characters.
This is a classic sliding window problem. We'll maintain a window [left, right] and use a hash map (or dictionary) to count the frequency of characters in the current window.
We'll expand the window by moving the right pointer, and when the number of distinct characters exceeds 2, we'll shrink the window from the left until we have at most 2 distinct characters again.
We keep track of the maximum length of the window that satisfies the condition.
Steps:
Initialize:
left = 0 (start of the window)
max_len = 0 (to store the length of the longest valid substring)
char_count = {} (dictionary to store frequency of characters in the current window)
Iterate right from 0 to len(s)-1:
Add s[right] to char_count (or increase its count).
While the number of keys in char_count > 2:
Decrease the count of s[left] in char_count.
If the count becomes 0, remove the key from char_count.
Increment left.
Now the window [left, right] has at most 2 distinct characters.
Update max_len = max(max_len, right - left + 1)
Return max_len.
However, note: we are asked for the longest substring, but the problem says "find the longest substring", and typically we return the substring itself or the length?
The problem statement says: "find the longest substring", so we might want to return the substring. But the example function signature is not given.
Let's assume we are to return the length, but the problem says "substring". We can adjust to return the substring by storing the start and end indices.
But the problem says: "Write a function to find the longest substring", so we should return the substring.
Let's adjust:
We'll keep track of:
max_len = 0
start = 0 (starting index of the longest substring found so far)
Then when we update max_len, we also update start = left.
But note: when we update max_len, we are at current right, and the current window is [left, right]. So the substring is s[left:right+1].
However, note that we are updating after shrinking the window? Actually, we update after ensuring the window is valid (at most 2 distinct). So the current window is valid.
So we can do:
if (right - left + 1) > max_len:
max_len = right - left + 1
start = left
Then at the end, return s[start:start+max_len]
But wait: what if there are multiple substrings of the same max length? We can return any one. So we'll return the first one we find with the max length?
Actually, we are updating when we find a longer one, so we'll return the last one that set the max? But if we want the first occurrence of the max length, we can change the condition to >=?
The problem doesn't specify which one to return. Let's return the first one we find with the maximum length? Actually, the typical approach is to update only when we find a longer one, so we'll get the last one that set the maximum.
But note: the window is moving, and we update max_len only when we have a longer window. So the substring we return will be the one that ends at the current right and has the maximum length. However, if there are multiple with the same length, we'll get the one that appears later?
Let's think:
Suppose we have a string "aabbaa", and we are looking for at most 2 distinct. The longest is "aabbaa" (6) but if we break it down:
Actually, "aabbaa" has two distinct? 'a' and 'b', so yes. But how does the algorithm work?
Alternatively, we can store the substring when we update max_len, but that might be inefficient because slicing is O(k). Instead, we store indices.
But note: the problem says "substring", so we have to return the substring.
Let's code accordingly.
However, the problem says: "write a function that solves this problem, and explain your algorithm". So we'll write the function and then explain.
But note: the problem says "Please this is a sliding window problem", so we must use sliding window.
Let's code:
def longest_substring_two_distinct(s):
if not s:
return ""
code
left = 0
max_len = 0
start = 0
char_count = {}
for right in range(len(s)):
# Add current character
char = s[right]
char_count[char] = char_count.get(char, 0) + 1
# Shrink the window until we have at most 2 distinct
while len(char_count) > 2:
left_char = s[left]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
left += 1
# Now the window [left, right] is valid
if right - left + 1 > max_len:
max_len = right - left + 1
start = left
return s[start:start+max_len]
But wait: what if the string has less than 2 distinct characters? Then the whole string is the answer.
However, note that the while loop condition: while len(char_count) > 2. So if we have 1 or 2, we don't shrink.
But what about the case when the string is empty? We return "".
Let's test with a simple example: s = "eceba" -> expected "ece" (or "ece" is one of the longest? Actually, "ece" has two distinct: 'e' and 'c'. Also "ceb" has two distinct? But "ece" is longer?
Actually, "ece" is 3, and "ceb" is 3, and "eba" is 3. So there are multiple of length 3. Our algorithm will return the first one that reaches length 3? Let's see:
Steps for "eceba":
right=0: char='e', char_count={'e':1}, window [0,0] -> max_len=1, start=0.
right=1: char='c', char_count={'e':1, 'c':1} -> window [0,1] -> max_len=2, start=0.
right=2: char='e', char_count={'e':2, 'c':1} -> window [0,2] -> max_len=3, start=0.
right=3: char='b', char_count={'e':2, 'c':1, 'b':1} -> now 3 distinct, so we shrink:
left=0: remove s[0]='e', char_count['e'] becomes 1, then left=1 -> still 3 distinct?
Actually, after removing s[0], we have char_count={'e':1, 'c':1, 'b':1} -> still 3?
Then remove s[1]='c': char_count['c'] becomes 0 -> remove key 'c', now char_count={'e':1, 'b':1} -> 2 distinct. left=2.
Now window [2,3] -> length 2, so max_len remains 3.
right=4: char='a', char_count={'e':1, 'b':1, 'a':1} -> 3 distinct, so shrink:
remove s[2]='e': char_count['e']=0 -> remove, left=3. Now char_count={'b':1, 'a':1} -> 2 distinct.
window [3,4] -> length 2.
So we return s[0:3] = "ece". That matches.
But note: there is another substring of length 3: "ceb". Our algorithm didn't return that because we only update when we find a longer one. Since 3 is not longer than 3, we don't update. So we return the first one that reached 3.
That is acceptable.
However, what if we have a longer substring later? We update only when we find a longer one, so we'll get the longest.
But what about if we have two substrings of the same maximum length? We return the first one we encountered? In the above, we returned the first one (starting at 0). But note: when we have a window of length 3 at right=2, we set start=0. Then at right=3, we have a window of length 2, so no update. At right=4, window length 2. So we return the first.
Expected: "accc" (or "ccca"? but the string is "abaccc", so the longest with at most 2 distinct is "accc" (or "bacc"? but "accc" is 4). Let's see:
right=0: 'a' -> window [0,0] -> max_len=1, start=0.
right=1: 'b' -> window [0,1] -> max_len=2, start=0.
right=2: 'a' -> window [0,2] -> max_len=3, start=0.
right=3: 'c' -> char_count={'a':2, 'b':1, 'c':1} -> 3 distinct, so shrink:
remove s[0]='a' -> char_count['a']=1, left=1 -> still 3 distinct? (a:1, b:1, c:1)
remove s[1]='b' -> char_count['b']=0 -> remove 'b', left=2. Now char_count={'a':1, 'c':1} -> 2 distinct.
window [2,3] -> length 2.
right=4: 'c' -> char_count={'a':1, 'c':2} -> window [2,4] -> length 3 -> update max_len=3, start=2? But wait, we had max_len=3 already? Actually, we had max_len=3 at right=2. Now at right=4, we have length 3, so we don't update because 3 is not greater than 3? But we want the longest, and we have a longer one later? Actually, at right=5 we will have 4.
But note: at right=4, we had a window of length 3 (from index 2 to 4: "acc") and we didn't update because 3<=3? Actually, we update only when strictly greater?
In our code: if (right - left + 1) > max_len: then update.
So at right=4, the window length is 3, and max_len is 3, so we don't update. Then at right=5, we get 4 and update.
That is correct.
However, what if we have two substrings of the same maximum length? We return the first one we found? In the above example, we returned the one starting at index 2. But note: there is also "bacc" (from index 1 to 4) which is also 4? Wait, "bacc" has 'b','a','c'? That's 3 distinct. So not valid.
So our algorithm returns the first occurrence of the maximum length? Actually, it returns the last one that set the maximum. But note: we update only when we find a longer one. So if we have two substrings of the same maximum length, we will return the first one that reached that maximum? Because when we get the second one of the same length, we don't update.
Example: s = "aabbcc"
The longest substring with at most 2 distinct:
"aabb" (length 4) and "bbcc" (length 4).
Let's run:
right=0: 'a' -> window [0,0] -> max_len=1, start=0.
right=1: 'a' -> window [0,1] -> max_len=2, start=0.
right=2: 'b' -> window [0,2] -> max_len=3, start=0.
right=3: 'b' -> window [0,3] -> max_len=4, start=0.
right=4: 'c' -> char_count: {'a':2, 'b':2, 'c':1} -> 3 distinct -> shrink:
remove s[0]='a' -> char_count['a']=1, left=1 -> still 3 distinct?
remove s[1]='a' -> char_count['a']=0 -> remove, left=2. Now char_count={'b':2, 'c':1} -> 2 distinct.
window [2,4] -> length 3 -> not update.
right=5: 'c' -> char_count={'b':2, 'c':2} -> window [2,5] -> length 4 -> update? 4>4? no, because 4 is not greater than 4. So we don't update.
So we return s[0:4] = "aabb". That is the first one.
If we want the last one, we can change the condition to >=? But then we would update and get the last one. The problem doesn't specify, so we can choose.
But note: the problem says "find the longest substring", so any longest is acceptable. We'll stick with the first one we find (by using >).
Alternatively, if we want the last one, we can use >=. But let's see the example: if we use >=, then at right=5 we update and start becomes 2, returning "bbcc".
Since the problem doesn't specify, I'll use > to return the first one.
But wait: what if the string is "abc"?
The longest substring with at most 2 distinct: "ab" or "bc", both length 2.
Our algorithm:
right=0: 'a' -> window [0,0] -> max_len=1, start=0.
right=1: 'b' -> window [0,1] -> max_len=2, start=0.
right=2: 'c' -> char_count={'a':1, 'b':1, 'c':1} -> shrink:
remove s[0]='a' -> left=1, char_count={'b':1, 'c':1} -> window [1,2] -> length 2 -> not update (because 2>2 is false).
So we return s[0:2] = "ab".
That's acceptable.
However, note: the problem says "no more than two distinct characters", so 0,1,2 are allowed.
Edge: empty string -> return "".
Let's code accordingly.
But wait: what if the string has only one character? Then we return the whole string.
This algorithm handles that because we never shrink (since we have at most 2 distinct).
So the code:
def longest_substring_two_distinct(s):
if not s:
return ""
code
left = 0
max_len = 0
start = 0
char_count = {}
for right in range(len(s)):
char = s[right]
char_count[char] = char_count.get(char, 0) + 1
while len(char_count) > 2:
left_char = s[left]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
left += 1
# Now window [left, right] is valid
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
start = left
return s[start:start+max_len]
However, note: we are using a dictionary and the while loop. The time complexity is O(n) because each character is added and removed at most once.
But wait: the while loop inside the for loop? Could it be O(n^2)?
Actually, each character is processed by the right pointer once, and the left pointer moves at most n times in total. So the inner while loop runs at most n times in total (amortized O(1) per right). So overall O(n).
Let's test with a few examples.
Example 1: s = "eceba" -> returns "ece"
Example 2: s = "ccaabbb" -> longest with 2 distinct: "aabbb" (5) or "ccaab" (5)? Actually, "aabbb" is 5 and "ccaab" is 5. Let's see:
code
We'll run the code:
right=0: 'c' -> window [0,0] -> max_len=1, start=0.
right=1: 'c' -> window [0,1] -> max_len=2, start=0.
right=2: 'a' -> window [0,2] -> max_len=3, start=0.
right=3: 'a' -> window [0,3] -> max_len=4, start=0.
right=4: 'b' -> char_count: {'c':2, 'a':2, 'b':1} -> 3 distinct -> shrink:
remove s[0]='c' -> char_count['c']=1, left=1 -> still 3 distinct?
remove s[1]='c' -> char_count['c']=0 -> remove, left=2. Now char_count={'a':2, 'b':1} -> 2 distinct.
window [2,4] -> length 3 -> not update.
right=5: 'b' -> char_count={'a':2, 'b':2} -> window [2,5] -> length 4 -> not update (4>4? no).
right=6: 'b' -> char_count={'a':2, 'b':3} -> window [2,6] -> length 5 -> update: max_len=5, start=2.
So we return s[2:7] = "aabbb". That is one of the longest.
Example 3: s = "abcabcabc" -> the longest with 2 distinct: "abab" or "bcbc" or "caca"? Actually, the longest is 4?
Let's see: we can have "abab" (from index0 to3) but that's 4? Actually, "abcabcabc" has three distinct. The longest with at most two distinct would be, for example, "ababa"? but that has 2? Actually, "ababa" has 'a' and 'b', so that's 2. But in the string, we have "abcabcabc", so we can have "abab" (from index0 to3) but that's only 4. Alternatively, we can have "bcbcb" (from index1 to5) which is 5? Let's check:
code
However, note: in the example "abcabcabc", we have multiple substrings of length 2. We return the first one.
But wait, what about the substring "bc"? That is also length2. But we return "ab".
That's acceptable.
Now, let's consider a case where we have a longer substring that appears later and is longer than the current max. We update.
So the algorithm is correct.
But note: we are using a dictionary and the while loop. We can also use a fixed-size array if the characters are limited (like ASCII). But the problem doesn't specify the character set, so we use dictionary.
Alternatively, we can use collections.Counter, but we are doing manual counting.
Now, let's write the function and then explain.
However, note: the problem says "write a function", so we must write the function.
But the problem also says "explain your algorithm". So we'll write the function and then explain.
Let me write the function with comments.
But note: the problem says "Please this is a sliding window problem", so we are expected to use sliding window.
Code:
def longest_substring_two_distinct(s: str) -> str:
if not s:
return ""
code
left = 0
max_len = 0
start = 0
char_count = {}
for right in range(len(s)):
# Add the current character to the window
char = s[right]
char_count[char] = char_count.get(char, 0) + 1
# If we have more than 2 distinct characters, shrink the window from the left
while len(char_count) > 2:
left_char = s[left]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
left += 1
# Check if the current window is the longest
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
start = left
return s[start:start+max_len]
Now, explanation:
We use a sliding window defined by [left, right]. We expand the window by moving right. We maintain a dictionary char_count that stores the frequency of each character in the current window.
When we add a new character at right, we update char_count. If the number of distinct characters (len(char_count)) becomes more than 2, we move the left pointer to the right until the window has at most 2 distinct characters. We do this by decrementing the count of the leftmost character and removing it from the dictionary if its count becomes 0.
After ensuring the window is valid, we check if the current window length (right-left+1) is greater than the maximum length we've seen so far. If so, we update max_len and record the starting index (left) of this window.
At the end, we return the substring from the recorded start index of length max_len.
Time complexity: O(n) where n is the length of the string. Each character is processed at most twice (once by right and once by left).
Space complexity: O(1) because the dictionary will have at most 3 keys (since we shrink when we have more than 2). So it's constant.
However, note: the dictionary can have up to 3 keys at any time (during the while loop we might have 3, but then we shrink to 2). So the space is O(1) (bounded by the number of distinct characters we allow, which is 2, but during the process we might have 3). So it's constant.
Let me adjust: the dictionary will have at most 3 keys (when we are in the while loop condition, we have 3, then we remove one). So it's O(1).
This meets the requirement.
But wait: what if the string has Unicode characters? The dictionary can have up to 3 keys, so still O(1).
So we are good.
However, note: the problem says "no more than two distinct characters", so we allow 0,1,2. Our algorithm handles that.
Let's test with an empty string: returns "".
Test with one character: returns that character.
Test with two distinct: returns the whole string.
So we are done.
But note: the problem says "find the longest substring", and we are returning the substring.
However, what if there are multiple substrings of the same maximum length? We return the first one we encountered (because we update only when we find a longer one). If we want the last one, we can change the condition to >=. But the problem doesn't specify, so we'll leave it as >.
Let me change to >= if we want the last one? Actually, if we use >=, then we update even when equal, so we get the last one. But the problem says "the longest", so any is acceptable.
I'll stick with >.
Now, let's write the function and then we can run some tests.
But note: the problem says "write a function", so we must write the function.
However, the user might expect the function to return the length? The problem says "substring", so we return the substring.
If the problem wanted the length, we could just return max_len. But we are returning the substring.
Let's write the function accordingly.
But wait: the problem says "find the longest substring", so we return the substring.
Code:
def longest_substring_two_distinct(s):
if not s:
return ""
code
left = 0
max_len = 0
start = 0
char_count = {}
for right in range(len(s)):
char = s[right]
char_count[char] = char_count.get(char, 0) + 1
while len(char_count) > 2:
left_char = s[left]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
left += 1
if right - left + 1 > max_len:
max_len = right - left + 1
start = left
return s[start:start+max_len]
Now, let's test with the examples we discussed.
Example: s = "eceba" -> returns "ece"
Example: s = "ccaabbb" -> returns "aabbb"
Example: s = "abcabcabc" -> returns "ab"
But wait, in "abcabcabc", the longest substring with at most two distinct is actually 2? We think so.
However, let me double-check:
The string: a b c a b c a b c
We can have "ab" (2), "bc" (2), "ca" (2). But what about "aba"? That would be from index0 to2? That's "abc" -> 3 distinct.
What about from index0 to3? "abca" -> 3 distinct.
code
So indeed, 2 is the maximum.
But wait, what about "aa"? There is no consecutive 'a's. So 2 is the maximum.
So the algorithm is correct.
However, note: there is a known problem "Longest Substring with At Most Two Distinct Characters" on LeetCode (problem 159). The above solution is standard.
Let me check with LeetCode example:
Input: "eceba" -> Output: 3 (which is the length of "ece"). Our function returns "ece".
So we are good.
But note: the problem says "substring", so we return the substring.
If the problem wanted the length, we could change the return to max_len.
Since the problem says "substring", we return the substring.
Now, the explanation:
We use a sliding window approach with two pointers (left and right) and a hash map to keep track of character frequencies in the current window.
Steps:
Initialize left=0, max_len=0, start=0, and an empty dictionary char_count.
Iterate right from 0 to n-1:
a. Add s[right] to char_count.
b. While the number of distinct characters (len(char_count)) exceeds 2:
i. Remove s[left] from the window by decrementing its count in char_count.
ii. If the count becomes 0, remove the key from char_count.
iii. Increment left.
c. Now the window [left, right] has at most 2 distinct characters.
d. If the current window length (right-left+1) is greater than max_len, update max_len and start.
Return the substring s[start:start+max_len].
Time complexity: O(n) because each character is processed at most twice (once by right and once by left).
Space complexity: O(1) because the dictionary has at most 3 keys.
That's it.
However, note: we are using a dictionary and the while loop. We can also use a fixed-size array for ASCII, but the problem doesn't specify the character set.
We'll stick with the dictionary.
Now, let's write the function in the required format.
But the problem says: "write a function that solves this problem". So we are done.
However, note: the problem says "You are given a string s." So the function takes a string s and returns a string.
We have written that.
Let me write the function again with type hints (if needed, but the problem doesn't specify). We can omit type hints.
But for clarity:
def longest_substring_two_distinct(s):
...
Now, we are done.
However, note: the problem says "explain your algorithm". We have explained in the comments and in the text above.
But the user might want a separate explanation. Since the problem says "and explain your algorithm", we can write the function and then explain.
But in the context of this response, we have already explained.
Let me structure the answer:
Function:
def longest_substring_two_distinct(s):
if not s:
return ""
code
left = 0
max_len = 0
start = 0
char_count = {}
for right in range(len(s)):
char = s[right]
char_count[char] = char_count.get(char, 0) + 1
while len(char_count) > 2:
left_char = s[left]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
left += 1
if right - left + 1 > max_len:
max_len = right - left + 1
start = left
return s[start:start+max_len]
Explanation:
We use a sliding window [left, right] to represent the current substring. We expand the window by moving right and include the new character in the frequency dictionary. If the number of distinct characters exceeds 2, we shrink the window from the left until we have at most 2 distinct characters. After each expansion (and possible shrinking), we check if the current window is the longest we've seen. We record the start index and length of the longest valid window. At the end, we return the substring from the recorded start index with the recorded length.
Time complexity: O(n) because each character is visited at most twice (once by right and once by left).
Space complexity: O(1) because the dictionary has at most 3 entries.
This is the standard solution for the problem.
However, note: the problem says "no more than two distinct characters", so we are allowing 0,1,2.
We are done.
But wait: what if the string has only one distinct character? Then we never enter the while loop, and we keep expanding and updating max_len. So we return the whole string.
That's correct.
Now, let's test with an example that has two distinct and then a third, and then back to two.
Example: s = "abaccc"
We already tested and it returns "accc".
So we are confident.
Now, note: the problem says "sliding window problem", so we used sliding window.
We are good.
However, there is an alternative approach that uses a fixed-size array for ASCII, but the dictionary approach is more general.
We'll stick with the dictionary.
Let me write the function again without comments for brevity? But the problem says "write a function", so we can write with comments.
But in the response, we can write the function and then the explanation.
Since the user asked to "explain your algorithm", we'll provide a clear explanation.
I think we have done.
Now, note: the problem says "Please this is a sliding window problem", so we must use sliding window. We did.
So we are done.
To solve this problem, we use a sliding window approach with two pointers (left and right) and a dictionary (char_count) to track the frequency of characters within the current window. The goal is to maintain a window that contains at most two distinct characters while maximizing its length.
Algorithm Steps:
Initialize:
left = 0 (start of the window)
max_len = 0 (length of the longest valid substring found)
start = 0 (starting index of the longest substring)
char_count = {} (dictionary to store character frequencies in the current window)
Expand the window by iterating right from 0 to len(s)-1:
Add s[right] to char_count (increment its count).
Shrink the window from the left if the number of distinct characters (len(char_count)) exceeds 2:
Decrement the count of s[left] in char_count.
If the count drops to 0, remove that character from char_count.
Increment left to reduce the window size.
After ensuring the window has ≤ 2 distinct characters, check if the current window length (right - left + 1) is greater than max_len. If so, update max_len and start.
Return the substring s[start:start+max_len].
Complexity Analysis:
Time Complexity: O(n) — Each character is processed at most twice (once by right, once by left).
Space Complexity: O(1) — The dictionary holds at most 3 entries (since we shrink when >2 distinct characters).
def longest_substring_two_distinct(s):
if not s:
return ""
left = 0
max_len = 0
start = 0
char_count = {}
for right in range(len(s)):
char = s[right]
char_count[char] = char_count.get(char, 0) + 1
# Shrink window until at most 2 distinct characters
while len(char_count) > 2:
left_char = s[left]
char_count[left_char] -= 1
if char_count[left_char] == 0:
del char_count[left_char]
left += 1
# Update longest substring if current window is longer
current_len = right - left + 1
if current_len > max_len:
max_len = current_len
start = left
return s[start:start + max_len]
This function efficiently finds the longest substring with at most two distinct characters using the sliding window technique.
Actually, the string is "abcabcabc", so:
indices: 0:a, 1:b, 2:c, 3:a, 4:b, 5:c, 6:a, 7:b, 8:c.
We can have "bcbcb" from index1 to5? That's 5 characters: b, c, b, c, b -> two distinct. But wait, at index1 to5:
index1: b, index2: c, index3: a -> that's three distinct. So we cannot have from index1 to5.
Actually, the longest with two distinct in this string is 4? Because every time we try to extend to 5, we get three distinct.
Let's run the algorithm:
We'll get:
right=0: 'a' -> window [0,0] -> max_len=1, start=0.
right=1: 'b' -> window [0,1] -> max_len=2, start=0.
right=2: 'c' -> char_count: {'a':1, 'b':1, 'c':1} -> shrink:
remove s[0]='a' -> left=1, char_count={'b':1, 'c':1} -> window [1,2] -> length 2 -> not update.
right=3: 'a' -> char_count: {'b':1, 'c':1, 'a':1} -> shrink:
remove s[1]='b' -> left=2, char_count={'c':1, 'a':1} -> window [2,3] -> length 2.
right=4: 'b' -> char_count: {'c':1, 'a':1, 'b':1} -> shrink:
remove s[2]='c' -> left=3, char_count={'a':1, 'b':1} -> window [3,4] -> length 2.
right=5: 'c' -> char_count: {'a':1, 'b':1, 'c':1} -> shrink:
remove s[3]='a' -> left=4, char_count={'b':1, 'c':1} -> window [4,5] -> length 2.
... and so on.
So we never get a window of length 3? Wait, let's check:
At right=3, after shrinking, we have window [2,3] which is "ca" (length2). Then at right=4, we add 'b', so we have "cab" -> 3 distinct, then we shrink to [3,4] which is "ab" (length2). So indeed, we never have 3.
But what about the substring "bcbc"? That would be from index1 to4? That's 4 characters: b,c,b,c? Actually, index1 to4:
index1: b, index2: c, index3: a, index4: b -> that's three distinct (b,c,a). So no.
The longest is 2? That can't be right. Let's think: in "abcabcabc", we can have "ab" (2), "bc" (2), "ca" (2). But wait, what about "aba"? That would be from index0 to3? That's 4 characters? No, index0 to3 is "abca": that's 3 distinct.
Actually, we cannot have a substring of length 3 with at most 2 distinct in this string? Because every three consecutive characters are all different?
"abc" -> 3 distinct.
"bca" -> 3 distinct.
"cab" -> 3 distinct.
So the maximum is 2. But wait, what about "aa"? There is no consecutive 'a's. So indeed, the maximum is 2.
But the example "abcabcabc" has no two consecutive same characters? Actually, it does:
The string is "a b c a b c a b c". So no two same in a row? Actually, the pattern is abc, so no two same adjacent.
So the longest substring with at most two distinct must be of length 2? Because if you take three, you get three distinct?
Let's try: take indices 0 and 1: "ab" -> 2 distinct -> valid.
Take indices 0,1,2: "abc" -> 3 distinct -> invalid.
Take indices 1,2,3: "bca" -> 3 distinct -> invalid.
So indeed, the maximum is 2.
But wait, what about taking non consecutive? The substring must be contiguous.
So the algorithm returns a substring of length 2? Let's see:
We update max_len only when we have a longer window. We start with max_len=1 at right=0.
At right=1: window [0,1] -> length2 -> update to 2, start=0.
Then from right=2 onward, we never get a window longer than 2? Because every time we add a new character, we have to shrink until we have at most 2, and then the window becomes length2? Actually, after right=2, we shrink to [1,2] (length2). Then at right=3, we add 'a' -> window becomes [1,3]? But then we have 'b','c','a' -> 3 distinct, so we shrink to [2,3] (length2). So we never get 3.
So we return s[0:2] = "ab". That is one of the longest (length2). There are multiple of length2.
So the algorithm works.