MediumNo. 0159LeetCode Premium
Longest Substring with At Most Two Distinct Characters — LeetCode 159 Python Solution
- Pattern
- Sliding Window
- Topics
- Hash Table, String, Sliding Window
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Given a string s, return the length of the longest substring that contains at most two distinct characters.
Example
- Input
- s = "eceba"
- Output
- 3
- Explanation
- The substring is "ece" which its length is 3.
Python solution
class Solution:
def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
cnt = Counter()
ans = j = 0
for i, c in enumerate(s):
cnt[c] += 1
while len(cnt) > 2:
cnt[s[j]] -= 1
if cnt[s[j]] == 0:
cnt.pop(s[j])
j += 1
ans = max(ans, i - j + 1)
return ansComplexity
- Time
- O(n)
- Space · auxiliary
- O(n)
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 159. Longest Substring with At Most Two Distinct Characters is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0003 | Longest Substring Without Repeating Characters | Medium |
| 0030 | Substring with Concatenation of All Words | Hard |
| 0076 | Minimum Window Substring | Hard |
| 0187 | Repeated DNA Sequences | Medium |
| 0395 | Longest Substring with At Least K Repeating Characters | Medium |
| 0424 | Longest Repeating Character Replacement | Medium |
Frequently asked questions
- How hard is LeetCode 159. Longest Substring with At Most Two Distinct Characters?
LeetCode 159. Longest Substring with At Most Two Distinct Characters is rated Medium on LeetCode.
- What is the time complexity of LeetCode 159. Longest Substring with At Most Two Distinct Characters?
The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 159. Longest Substring with At Most Two Distinct Characters?
The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 159. Longest Substring with At Most Two Distinct Characters cover?
LeetCode 159. Longest Substring with At Most Two Distinct Characters is tagged Hash Table, String and Sliding Window on LeetCode.
- Is LeetCode 159. Longest Substring with At Most Two Distinct Characters a premium problem?
Yes. LeetCode 159. Longest Substring with At Most Two Distinct Characters is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.