⚡Flashcard Drill➔
NeetCode #242LC-1358MediumSliding Window
← Back to All Problems

#242 · #1358 · Number of Substrings Containing All Three Characters(包含所有三种字符的子字符串数目)

📌 Problem Statement & Constraints

Given a string s consisting only of the characters a, b and c, return the number of substrings containing at least one occurrence of each of the three characters. Constraints: 3 <= s.length <= 5 * 10^4.

💡 Core Algorithmic Approaches

  1. Maintain a window that always contains at least one of each character by shrinking from the left whenever it is complete.
  2. For each right endpoint, after shrinking to the minimal complete window [l, r], every start index from 0 to l - 1 yields a valid substring ending at r.
  3. So add l to the answer for each right endpoint.
  4. Each pointer moves monotonically, giving O(n) overall.

💻 Benchmark Python3 Implementation

class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        cnt = [0, 0, 0]
        l = 0
        res = 0
        for r, ch in enumerate(s):
            cnt[ord(ch) - 97] += 1
            while all(c > 0 for c in cnt):     # window contains all three
                cnt[ord(s[l]) - 97] -= 1
                l += 1
            # every start in [0, l-1] yields a valid substring ending at r
            res += l
        return res

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): each pointer moves monotonically; the all(...) check is over three counters.
💾 Space Complexity
O(1): a length-3 counter array.

⚠️ Interview Pitfalls & Follow-ups

  • Counting only the minimal window: the number of valid substrings ending at r is l, not 1.
  • Shrinking before checking completeness: the shrink must happen while the window is complete, and the answer accumulates l after shrinking.
  • Using a set to check completeness: a counter is needed because the window may contain multiple copies of a character, and the shrink must not remove the last one prematurely.
  • Forgetting the modulo in the character-to-index mapping: ord(ch) - ord('a') gives 0, 1, 2 for a, b, c.
⚡
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,它只包含三种字符 a 、 b 和 c 。请你返回 a 、 b 和 c 都至少出现过一次 的子字符串数目。约束:3 ≤ s.length ≤ 5 × 10^4;s 只含 a 、 b 、 c 。

核心要点

  • 记录每种字符的最近位置(标准解) :遍历 s,维护 last[a] 、 last[b] 、 last[c] 三个「最近出现下标」。
  • 以 i 结尾的合法子串数 :以 i 结尾且包含三种字符的子串,其左端点可以取 0..min(last) ,共 min(last) + 1 个。
  • 为什么是 min(last) + 1 :左端点必须 ≤ 三种字符最近出现位置的最小值,才能保证窗口内三种字符都出现。
  • 累加 :把所有 i 的贡献相加即为答案。

常见陷阱

  • 用滑动窗口 + 累加 n − r 的写法 :也正确,但需要维护「窗口内各字符计数」并处理收缩,实现更复杂。位置法一行搞定。
  • 忘记 +1 :左端点可以取到 min(last) 本身(此时窗口左端恰好是某个字符的最近位置),因此是 min(last) + 1 个。
  • 初始值设为 0 而非 −1 :初值必须是 −1,表示「尚未出现」。若为 0,当某字符还没出现时会错误地把下标 0 当作它的位置。
  • 统计「恰好包含」而非「至少包含」 :题目要求至少各出现一次,位置法天然满足。

参考实现

class Solution:
    def numberOfSubstrings(self, s: str) -> int:
        last = {'a': -1, 'b': -1, 'c': -1}
        res = 0
        for i, c in enumerate(s):
            last[c] = i
            # 以 i 结尾的合法子串,左端点可取 0..min(last),共 min(last)+1 个
            res += min(last.values()) + 1
        return res