⚡Flashcard Drill➔
NeetCode #226LC-159MediumSliding WindowNC Algo100
← Back to All Problems

#226 · #159 · Longest Substring with At Most Two Distinct Characters(至多包含两个不同字符的最长子串)

📌 Problem Statement & Constraints

Given a string s, find the length of the longest substring that contains at most two distinct characters. Constraints: 1 <= s.length <= 10^4; s consists of ASCII characters.

💡 Core Algorithmic Approaches

  1. Sliding window with a frequency map: expand the right end and shrink from the left while the map holds more than two distinct characters.
  2. When a character's count drops to zero while shrinking, remove the key so the distinct count is accurate.
  3. The window length is the candidate answer.
  4. This is the k = 2 case of the general At Most K Distinct Characters problem.

💻 Benchmark Python3 Implementation

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        from collections import defaultdict
        cnt = defaultdict(int)
        l = 0
        best = 0
        for r, ch in enumerate(s):
            cnt[ch] += 1
            while len(cnt) > 2:        # too many distinct characters
                cnt[s[l]] -= 1
                if cnt[s[l]] == 0:
                    del cnt[s[l]]
                l += 1
            best = max(best, r - l + 1)
        return best

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each character enters and leaves the window at most once.
💾 Space Complexity
O(1): the map holds at most 3 entries.

⚠️ Interview Pitfalls & Follow-ups

  • Not deleting zero-count keys: len(cnt) would overcount the distinct characters and the window would shrink too far.
  • Using >= 2 in the while condition: the limit is *at most* two, so the condition is > 2.
  • Tracking the distinct count manually: deleting keys is simpler and less error-prone.
  • Assuming the answer is always 2: a string of a single repeated character gives the whole length.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Sliding Window Problems

中文速览与面试要点

至多包含两个不同字符的最长子串

给你一个字符串 s,请你找出 至多 包含 两个不同字符 的最长子串,并返回该子串的长度。约束:1 ≤ s.length ≤ 10^5;s 由英文字母组成。

核心要点

  • 滑动窗口 + 字符计数(标准解) :维护窗口内各字符的计数。当不同字符数超过 2 时,收缩左边界直到满足条件。
  • 删除零计数键 :收缩时若某字符计数降为 0,必须从字典中删除,否则 len(cnt) 不会减少,while 循环无法退出。
  • 为什么 len(cnt) 就是不同字符数 :前提是字典中不保留零计数键——这正是上一条的关键。
  • 推广 :把 2 换成 k 即为 340 题。

常见陷阱

  • 不删除零计数键 : len(cnt) 会一直大于 2,while 循环死循环或窗口被错误地收缩到极短。这是本题第一大坑。
  • 用集合而非计数 :集合无法反映字符出现次数,且收缩时难以判断何时应移除字符。
  • 收缩时用 if 而非 while :一次收缩可能不足以让不同字符数降到 2(例如窗口内有 3 个字符各出现多次),必须用 while。
  • 误以为要求「恰好两个」 :题目是「至多两个」,因此全为同一字符时也合法(答案为 n)。

参考实现

from collections import defaultdict

class Solution:
    def lengthOfLongestSubstringTwoDistinct(self, s: str) -> int:
        cnt = defaultdict(int)
        l = 0
        best = 0
        for r, c in enumerate(s):
            cnt[c] += 1
            while len(cnt) > 2:             # 不同字符超过 2 个
                cnt[s[l]] -= 1
                if cnt[s[l]] == 0:
                    del cnt[s[l]]           # 关键:清理零计数键
                l += 1
            if r - l + 1 > best:
                best = r - l + 1
        return best