Number of Substrings Containing All Three Characters
Problem Statement
You are given a string s made only of the letters a, b and c.
Count how many substrings contain at least one a, at least one b and at least one c.
A string s containing only the characters a, b, c.
The number of substrings that contain all three letters.
The good substrings are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (the last one starting at index 3).
The good substrings are "aaacb", "aacb" and "acb".
Only the whole string has all three letters.
- • 3 ≤ s.length ≤ 5·10^4
- • s contains only 'a', 'b' and 'c'.
- • The answer is at most n(n+1)/2 ≈ 1.25·10^9, which still fits in an int, but n·(n+1) does not.
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
For each start, grow until all three letters appear, then add n − end
All substrings minus the ones with at most 2 distinct letters
While the window has a, b, c, add n − right and shrink from the left
Fix a start. Grow the end and count letters. The first time all three letters are present, every longer substring from this start is also good, so add n − end and move to the next start.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Sliding Window translate into production architectures and low-level memory mechanics.