Number of Substrings Containing All Three Characters - Problem

Given a string s consisting only of characters a, b and c.

Return the number of substrings containing at least one occurrence of all these characters a, b and c.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcabc"
Output: 10
💡 Note: Substrings containing all three: "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc", "abc" (from position 3-5)
Example 2 — Minimum Valid
$ Input: s = "aaacb"
Output: 3
💡 Note: After seeing all three chars at position 4, substrings "aaacb", "aacb", "acb" contain a, b, and c
Example 3 — No Valid Substrings
$ Input: s = "abc"
Output: 1
💡 Note: Only one substring "abc" contains all three characters

Constraints

  • 3 ≤ s.length ≤ 5 × 104
  • s only consists of 'a', 'b' or 'c' characters.

Visualization

Tap to expand
Problem: Count Substrings with All Three CharactersInput: s = "abcabc"abcabcValid substrings (containing a, b, AND c):abc (0-2)abca (0-3)abcab (0-4)abcabc (0-5)+ 6 more...Output: 10
Understanding the Visualization
1
Input
String s with only characters a, b, c
2
Process
Find substrings containing all three characters
3
Output
Count of valid substrings
Key Takeaway
🎯 Key Insight: Once we find all three characters, every extension creates more valid substrings
Asked in
Amazon 15 Microsoft 8
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen