Given a string s and an integer k, return the length of the longest substring of s such that the frequency of each character in this substring is at least k.
s?
s contain?
s contains only lowercase English letters.k be greater than the length of the string s?
k times.s be empty?
s is empty, the function should return 0.k times, then it cannot be part of the substring we are looking for.k times.Here is the plan:
s.s at characters whose frequency is less than k.def longestSubstring(s: str, k: int) -> int:
def helper(substring: str) -> int:
if len(substring) == 0:
return 0
# Frequency count of characters
freq = {}
for char in substring:
if char in freq:
freq[char] += 1
else:
freq[char] = 1
for char in freq:
if freq[char] < k:
# Split by this character and recursively solve
return max(helper(part) for part in substring.split(char))
# All characters meet or exceed k frequency
return len(substring)
return helper(s)
# Example usage:
s = "aaabb"
k = 3
print(longestSubstring(s, k)) # Output: 3
n is the length of the string and m is the number of unique characters in the string. Here’s the breakdown:
m where m is limited by the number of unique characters (at most 26 for lowercase English letters).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?