Probably not the most optimal solution but passed:

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        if len(s) == 1: return 1
 
        l, r = 0, 0
        length = 1
        chars = defaultdict(int)
 
        while r < len(s):
            if s[r] in chars or len(chars) < 2:
                chars[s[r]] += 1
                length = max(length, r - l + 1)
            else:
                chars[s[r]] += 1
                while len(chars) > 2:
                    chars[s[l]] -= 1
                    if chars[s[l]] == 0:
                        del chars[s[l]]
                    l += 1
            
            r += 1
            
        return length
            

Complexity

Time: (TODO: Not sure, but probably is the case since there’re nested loops)
Space: because dictionary size is fixed since there is limited set of characters