Find Longest Special Substring That Occurs Thrice II Problem
Description
LeetCode Problem 2982.
You are given a string s that consists of lowercase English letters.
A string is called special if it is made up of only a single character. For example, the string "abc" is not special, whereas the strings "ddd", "zz", and "f" are special.
Return the length of the longest special substring of s which occurs at least thrice, or -1 if no special substring occurs at least thrice.
A substring is a contiguous non-empty sequence of characters within a string.
Example 1:
Input: s = "aaaa"
Output: 2
Explanation: The longest special substring which occurs thrice is "aa": substrings "aaaa", "aaaa", and "aaaa".
It can be shown that the maximum length achievable is 2.
Example 2:
Input: s = "abcdef"
Output: -1
Explanation: There exists no special substring which occurs at least thrice. Hence return -1.
Example 3:
Input: s = "abcaba"
Output: 1
Explanation: The longest special substring which occurs thrice is "a": substrings "abcaba", "abcaba", and "abcaba".
It can be shown that the maximum length achievable is 1.
Constraints:
3 <= s.length <= 5 * 10^5sconsists of only lowercase English letters.
Solution
Approach: Binary Search + Counting Runs
The answer is monotone: if a special substring of length x occurs at least three times, then one of length x - 1 does too (just drop one character from each occurrence). So we can binary search on the length.
For a candidate length x, split the string into maximal runs of one repeated letter. A run of length L contains max(0, L - x + 1) special substrings of length x, all made of the same letter. Add these up per letter; if some letter reaches a total of 3, length x works.
The search runs over 0..n; if the best length is 0, return -1.
Complexity: O(n log n) time and O(1) extra space (26 counters).
from collections import defaultdict
class Solution:
def maximumLength(self, s: str) -> int:
def check(x: int) -> bool:
cnt = defaultdict(int)
i = 0
while i < n:
j = i + 1
while j < n and s[j] == s[i]:
j += 1
cnt[s[i]] += max(0, j - i - x + 1)
i = j
return max(cnt.values()) >= 3
n = len(s)
l, r = 0, n
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return -1 if l == 0 else l