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

#227 · #340 · Longest Substring with At Most K Distinct Characters(至多包含 K 个不同字符的最长子串)

📌 Problem Statement & Constraints

Given a string s and an integer k, return the length of the longest substring that contains at most k distinct characters. Constraints: 1 <= s.length <= 5 * 10^4, 0 <= k <= 50; s consists of ASCII characters.

💡 Core Algorithmic Approaches

  1. Generalise the two-distinct-character window: shrink while the map holds more than k distinct characters.
  2. Delete keys whose count reaches zero so the distinct count stays accurate.
  3. The window length is the candidate answer.
  4. With k = 0 the answer is 0, which the general code handles if the window never becomes non-empty -- verify that the shrink loop empties it.

💻 Benchmark Python3 Implementation

class Solution:
    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
        from collections import defaultdict
        if k == 0:
            return 0                   # no character is allowed
        cnt = defaultdict(int)
        l = 0
        best = 0
        for r, ch in enumerate(s):
            cnt[ch] += 1
            while len(cnt) > k:
                cnt[s[l]] -= 1
                if cnt[s[l]] == 0:
                    del cnt[s[l]]      # keep the distinct count accurate
                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(k) for the frequency map.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the k == 0 guard: without it, the shrink loop would empty the window every iteration and the answer would still be 0, but the extra work is pointless -- and in some formulations the loop could misbehave.
  • Not deleting zero-count keys: the distinct count would be wrong.
  • Assuming the alphabet is small: the general map-based approach works for any alphabet, unlike a fixed 26-array.
  • Using >= k in the condition: the limit is *at most* k.
⚡
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

中文速览与面试要点

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

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

核心要点

  • 滑动窗口 + 字符计数(标准解) :与 159 题完全同构,只把「2」替换为参数 k。
  • 删除零计数键 : len(cnt) 表示窗口内不同字符数,因此收缩时必须删除计数为 0 的键。
  • k == 0 的边界 :此时任何非空子串都不合法,应返回 0。
  • 复杂度 :O(n) 时间、O(k) 空间。

常见陷阱

  • 忘记处理 k == 0 :此时 len(cnt) &gt; 0 对任何非空窗口都成立,while 会把窗口收缩到空,虽然循环能退出但逻辑上应显式返回 0。
  • 不删除零计数键 :导致 len(cnt) 无法下降,窗口被错误收缩。
  • 把 while 写成 if :一次收缩可能不足。
  • 误以为 k 可以大于字符集大小 :k ≤ 50 而英文字母有 52 个(大小写),因此可能超出实际不同字符数,此时答案就是 n。

参考实现

from collections import defaultdict

class Solution:
    def lengthOfLongestSubstringKDistinct(self, s: str, k: int) -> int:
        if k == 0:
            return 0                        # 边界:不允许任何字符
        cnt = defaultdict(int)
        l = 0
        best = 0
        for r, c in enumerate(s):
            cnt[c] += 1
            while len(cnt) > k:
                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