1358. Number of Substrings Containing All Three Characters
Description
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.
Example 1:
Input: s = "abcabc" Output: 10 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "abc", "abca", "abcab", "abcabc", "bca", "bcab", "bcabc", "cab", "cabc" and "abc" (again).
Example 2:
Input: s = "aaacb" Output: 3 Explanation: The substrings containing at least one occurrence of the characters a, b and c are "aaacb", "aacb" and "acb".
Example 3:
Input: s = "abc" Output: 1
Constraints:
3 <= s.length <= 5 x 104sonly consists of'a','b'or'c'characters.
Solutions
Solution 1: Single Pass
Thinking
Count substrings that contain \(a\), \(b\), and \(c\). \(n \le 5 \times 10^4\) rules out both endpoints. With right end \(i\), every left end at most the earliest of the three last-seen positions is valid. Tracking those three indices, we add \(\min(d[a],d[b],d[c])+1\) at each \(i\).
We use an array \(d\) of length \(3\) to record the most recent occurrence of the three characters, initially all set to \(-1\).
We traverse the string \(s\). For the current position \(i\), we first update \(d[s[i]]=i\), then the number of valid strings is \(\min(d[0], d[1], d[2]) + 1\), which is accumulated to the answer.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(s\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
Solution 2: Sliding Window
Thinking
The first method uses last-seen indices. A counting window works as well: after extending \(r\), shrink \(l\) while all three letters remain, then add the current \(l\) as the number of valid left ends. Both are linear; the window never stores last positions.
We can solve this using a sliding window. Maintain a window \([l, r]\) and an array \(\textit{cnt}\) recording the frequency of each character in the window.
Traverse the string and keep moving the right boundary \(r\) to include \(s[r]\). If the window contains at least one \(a\), \(b\), and \(c\), keep moving the left boundary \(l\) to the right until the window no longer contains all three characters.
At this point, all substrings ending at \(r\) that contain \(a\), \(b\), and \(c\) can start at indices \(0, 1, \ldots, l - 1\), giving \(l\) valid substrings in total. Add this count to the answer.
The time complexity is \(O(n)\), where \(n\) is the length of the string \(s\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |