Problem Description
Given a string s composed only of lowercase English letters, a substring is called special if it consists of exactly one distinct character (e.g., "aaa" or "zz"). The task is to determine the length of the longest special substring that occurs at least three times in s (overlapping occurrences count). If no such substring exists, return -1.
Key Insights
- The special substring can only be formed by consecutive identical characters.
- For any contiguous run of the same letter with length k, it produces (k - L + 1) substrings of length L.
- We can aggregate counts by letter across all runs.
- The count function for a fixed letter is monotonic with respect to L (if a certain L is achievable, so are smaller ones).
- Use binary search over possible substring lengths to efficiently find the maximum L for which any letter produces at least 3 occurrences.
Space and Time Complexity
Time Complexity: O(26 * R * log(max_run)) where R is the number of runs (in worst-case O(n)) and max_run is the maximum run length in s.
Space Complexity: O(n) for storing run information.
Solution
The solution starts by traversing string s to identify runs of consecutive identical characters. We then use binary search over the possible substring lengths (from 1 to the maximum run length). For each candidate length L, for each letter we sum the counts from its runs (each contributing max(0, run_length - L + 1)). If any letter has a total count of at least three, L is valid. Continue with binary search to locate the maximum L meeting the criteria. Finally, if a valid special substring exists, its length is returned; otherwise, return -1.