## Description

https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/

Given a string ** s** , find the length of the longest substring

**that contains**

*t***at most**2 distinct characters.

**Example 1:**

Input:"eceba"Output:3Explanation:is "ece" which its length is 3.t

**Example 2:**

Input:"ccaabbb"Output:5Explanation:is "aabbb" which its length is 5.t

## Explanation

Two pointers. Keep faster pointer moving to the right until more than 2 distinct characters. Then adjust slower pointer and repeat the same.

## Python Solution

```
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
if not s:
return ""
max_length = 1
j = 0
counter = {}
for i in range(len(s)):
while j < len(s) and (len(counter) < 2 or (len(counter) == 2 and s[j] in counter)):
counter[s[j]] = counter.get(s[j], 0) + 1
j += 1
if len(counter) <= 2:
max_length = max(max_length, j - i)
counter[s[i]] -= 1
if counter[s[i]] == 0:
del counter[s[i]]
return max_length
```

- Time Complexity: ~N
- Space Complexity: ~1

where N is a number of characters in the input string.