Problem Description
Given a string s that consists only of characters a, b, and c, return the number of substrings that contain at least one occurrence of each of these characters.
Key Insights
- Use the sliding window technique to efficiently capture a valid window containing at least one a, one b, and one c.
- For every valid window, all substrings ending after the right pointer are valid, so you can count them in constant time.
- Shrinking the window from the left while maintaining validity helps in counting all possible substrings without reprocessing the entire string.
Space and Time Complexity
Time Complexity: O(n) – Each character is processed at most twice (once when expanding the window and once when contracting it).
Space Complexity: O(1) – Only a fixed-size dictionary (or array) is used to count occurrences of a, b, and c.
Solution
The solution uses a sliding window approach with two pointers (left and right). We expand the right pointer to include new characters while maintaining a count of each character. Once the window is valid (contains at least one a, one b, and one c), we know that any substring starting from the left index and ending at any index from right to the end of the string is valid. Therefore, we add (n - right) to our result, where n is the length of the string. We then shrink the window from the left to explore new windows. This ensures that we count each valid substring exactly once.