Problem
Given a strings, return the length of the longest substring that contains at most two distinct characters.
Examples
Constraints
- 1 <= s.length <= 10^5
- s consists of English letters
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 159 with 19 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 159 # by problem number
lcpy gen -s longest_substring_with_at_most_two_distinct_characters # by problem name
s, return the length of the longest substring that contains at most two distinct characters.
Input: s = "eceba"
Output: 3
Explanation: The substring is "ece" which its length is 3.
Input: s = "ccaabbb"
Output: 5
Explanation: The substring is "aabbb" which its length is 5.
class Solution:
# Time: O(n)
# Space: O(1)
def length_of_longest_substring_two_distinct(self, s: str) -> int:
count: dict[str, int] = {}
left = 0
longest = 0
for right, ch in enumerate(s):
count[ch] = count.get(ch, 0) + 1
while len(count) > 2:
left_ch = s[left]
count[left_ch] -= 1
if count[left_ch] == 0:
del count[left_ch]
left += 1
longest = max(longest, right - left + 1)
return longest
| Time | Space |
|---|---|
| O(n) | O(1) |