Problem Description
Given a string s, count the number of substrings of length three that have all distinct characters. A substring is a contiguous block of characters, and if there are multiple occurrences of the same substring, every occurrence is counted.
Key Insights
- The problem involves checking every substring of fixed length (3) in the string.
- A substring is considered "good" if all three characters are distinct.
- The sliding window technique is optimal since the window size is fixed.
- A simple check using a set can determine if all characters in the substring are distinct.
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string. We traverse the string once. Space Complexity: O(1), since the fixed-size substring (set of at most 3 characters) uses constant space.
Solution
We use the sliding window approach to consider every contiguous substring of length 3. For each window, we convert the substring to a set and check if its size is 3, meaning all characters are unique. We then increment a counter for each valid substring. This approach is efficient due to the fixed window size and minimal operations for each window.