Skip to main content

395. Longest Substring with At Least K Repeating Characters

link

Not the common pattern. We use slide window with restricted condition.

class Solution:
def longestSubstring(self, s: str, k: int) -> int:

n = len(set(s))

res = 0

def helper(pairN):
M = defaultdict(int)
l = 0
S = set()
count = 0
res = 0
for i in range(len(s)):
M[s[i]] += 1
S.add(s[i])

if M[s[i]] == k:
count += 1

while len(S) > pairN:
M[s[l]] -= 1
if M[s[l]] == k - 1:
count -= 1
if M[s[l]] == 0:
S.remove(s[l])
l += 1

if len(S) == pairN and count == pairN:
res = max(res, i - l + 1)

return res

for i in range(1, n+1):
res = max(res, helper(i))

return res