Find Longest Special Substring That Occurs Thrice I
Algoright/BinarySearch
Intuition
To solve the problem, we can uses binary search over the possible values of x, combined with a validation function to check the constraints.
Approach
Below is the step-by-step breakdown of the approach:
-
Binary Search Setup:
- The range of x is from 0 to n (length of the string).
- We perform binary search to find the maximum x that satisfies the condition.
-
Validate Possible:
- Checks whether there exists a character in s that appears consecutively at least x times.
-
Update the Binary Search Range:
- If
check(mid)
returns true, it means mid satisfies the condition, and we move the lower bound l to mid. - Otherwise, move the upper bound r to
mid - 1
.
- If
-
Return Result:
- If l is 0, it means no valid satisfies the condition, so return -1. Otherwise, return l.
Complexity
- Time Complexity: , binary search has iterations, each call to check involves a linear traversal of the string cause .
- Space Complexity: , the
cnt
array has a constant size of 26.