Longest Substring with At Most Two Distinct Characters Problem
Description
LeetCode Problem 159.
Given a string s, return the length of the longest substring that contains at most two distinct characters.
Example 1:
Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.
Example 2:
Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.
Constraints:
1 <= s.length <= 10^5sconsists of English letters.
Solution
Approach: Sliding Window
Checking every substring takes O(n2) time or worse. Instead we keep a window s[left..right] that always holds at most two distinct characters, and a count of each character in it.
Move right across the string one character at a time and add s[right] to the counts. If the window now has three distinct characters, move left forward, removing characters from the counts, until one of the three kinds has a count of zero. The window is then valid again, and its length right - left + 1 is a candidate for the answer.
Why is it safe to move left and never move it back? If s[left..right] has three kinds of characters, then every window that starts at or before left and ends at right or later has them too, so none of those can be the answer.
Keep a running count of distinct characters (or the size of a hash map) so the check is O(1). Note that the string has upper and lowercase letters, and 'a' and 'A' are different characters.
Complexity: O(n) time, since each pointer moves at most n times. O(1) extra space: the window holds at most three kinds of characters.
from collections import Counter
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
count = Counter() # characters in the window s[left..right]
ans = left = 0
for right, c in enumerate(s):
count[c] += 1
while len(count) > 2: # three kinds: shrink from the left until one is gone
count[s[left]] -= 1
if count[s[left]] == 0:
del count[s[left]]
left += 1
ans = max(ans, right - left + 1)
return ans