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
Number of Substrings Containing All Three Characters INPUT String s = "abcabc" a 0 b 1 c 2 a 3 b 4 c 5 Length: 6 Characters: a, b, c Valid Substrings: "abc" [0-2] "abca" [0-3] "abcab" [0-4] "abcabc"[0-5] "bca" [1-3] "bcab" [1-4] "bcabc" [1-5] ALGORITHM STEPS 1 Track Last Position Store last index of a, b, c 2 Iterate String For each position i 3 Find Minimum min(last[a], last[b], last[c]) 4 Add Count count += min + 1 Iteration Example i=0: last=[0,-1,-1] min=-1 +0 i=1: last=[0,1,-1] min=-1 +0 i=2: last=[0,1,2] min=0 +1 i=3: last=[3,1,2] min=1 +2 i=4: last=[3,4,2] min=2 +3 i=5: last=[3,4,5] min=3 +4 Total: 0+0+1+2+3+4 = 10 FINAL RESULT Output 10 OK - Valid Count Count Breakdown: Starting at 0: 4 substrings Starting at 1: 3 substrings Starting at 2: 2 substrings Starting at 3: 1 substring 4 + 3 + 2 + 1 = 10 Time: O(n) | Space: O(1) Single pass solution Key Insight: For each position i, if we know the minimum last position (minPos) where all three characters appeared, then all substrings starting from index 0 to minPos and ending at i are valid. This gives us (minPos + 1) valid substrings for each position, allowing O(n) time complexity with just 3 variables tracking last positions. TutorialsPoint - Number of Substrings Containing All Three Characters | Optimal Solution
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