The most direct approach is to examine every possible substring and check if it contains at most two distinct characters. For each starting position, we extend the substring character by character, tracking the distinct characters seen. Once we see a third distinct character, we stop and record the maximum valid length found.
res = 0 to store the maximum length.i from 0 to n-1:seen to track distinct characters.curLen = 0.j from i to n-1:s[j] to the set.2, break out of the inner loop.curLen.res = max(res, curLen).res.We maintain a window that always contains at most two distinct characters. As we expand the window to the right, we track character frequencies in a hash map. When adding a new character causes us to have more than two distinct characters, we shrink the window from the left until we're back to two or fewer distinct characters.
res = 0, j = 0 (left pointer), and a hash map seen for character counts.i (right pointer) from 0 to n-1:s[i] in the map.2 distinct characters:s[j].0, remove s[j] from the map.j.res = max(res, i - j + 1).res.class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
res, n = 0, len(s)
seen = defaultdict(int)
j = 0
for i in range(n):
seen[s[i]] += 1
while len(seen) > 2:
seen[s[j]] -= 1
if seen[s[j]] == 0:
seen.pop(s[j])
j += 1
res = max(res, i - j + 1)
return resWe can further optimize by observing that we only care about the maximum window size. Instead of tracking the actual maximum during iteration, we maintain a window that never shrinks by more than one element at a time. When we have too many distinct characters, we shift the entire window right by one. The final window size represents the longest valid substring.
j = 0 (left pointer) and a hash map count for character frequencies.i from 0 to n-1:s[i].2 distinct characters:s[j].0, remove from map.j.i - j + 1 (or n - j after the loop).When shrinking the window from the left, you must remove characters from the hash map when their count drops to zero. If you only decrement the count without removing the entry, the map size will incorrectly reflect more distinct characters than actually exist in the window, causing premature window shrinking.
The problem asks for substrings with at most two distinct characters, not exactly two. This means substrings with zero or one distinct character are also valid. Ensure your solution counts these cases correctly and does not skip windows with fewer than two distinct characters.
A common mistake is updating the result before fully adjusting the window to be valid. Always ensure the window contains at most two distinct characters before calculating and updating the maximum length. Update the result after the while loop that shrinks the window, not before.