[
greedy
string
]
BinarySearch 0685 Shortest Majority Substring
Problem statement
https://binarysearch.com/problems/Shortest-Majority-Substring/
Solution
In fact, answer can be -1, 2 or 3. Imagine, that we have string with length > 3. Then we can remove some symbols from the start and from the end, which is not equal to the most frequent symbol, so we have x....x. If we have x...xx, then we have answer of length 2, in the opposite case we can remove last two symbols and have shorter string.
Complexity
It is O(n) for time and space.
Code
class Solution:
def solve(self, s):
n = len(s)
for i in range(n - 1):
if s[i] == s[i + 1]: return 2
for i in range(n - 2):
if s[i] == s[i + 2]: return 3
return -1