Problem Description
Given a string s consisting only of lowercase English letters, we need to count the number of special substrings. A substring is considered special if it does not contain any repeating characters. For example, in "pop", the substring "po" is special whereas "pop" is not because 'p' appears twice.
Key Insights
- We are asked to count all substrings that do not have a repeated character.
- A valid special substring is defined by a contiguous segment with all unique characters.
- We can use the sliding window technique to efficiently enumerate substrings that satisfy the constraints.
- For each position in the string (as the end of the window), the number of valid substrings ending at that position equals the length of the current window (i.e., the number of choices for the starting position).
Space and Time Complexity
Time Complexity: O(n), where n is the length of the string since each character is processed at most twice. Space Complexity: O(1) in practice, as the structure used to track characters will have at most 26 keys (the number of lowercase letters).
Solution
We use the sliding window technique with two pointers (left and right). The idea is to maintain a window that always contains unique characters. As we move the right pointer to explore new characters, if a duplicate is encountered, we move the left pointer until the duplicate is removed from the current window. At every step, the size of the valid window gives the count of new special substrings ending at the current index. By summing these counts up for every index, we obtain the total number of special substrings.