Given a string s and an integer k, return the length of the longest substring ofssuch that the frequency of each character in this substring is greater than or equal tok.
To solve the problem of finding the length of the longest substring in s such that the frequency of each character in this substring is greater than or equal to k, the idea is to use a divide-and-conquer strategy.
Here are the steps:
Frequency Calculation:
Calculate the frequency of each character in the string.
Divide and Conquer:
If a character’s frequency is less than k, then this character cannot be part of the valid substring. This splits the problem into smaller substrings.
Recursively check each of these substrings to find the longest valid substring.
Base Case:
If every character in the string meets the frequency requirement, return the length of the string.
publicclassSolution {
publicintlongestSubstring(String s, int k) {
return longestSubstringHelper(s, 0, s.length(), k);
}
privateintlongestSubstringHelper(String s, int start, int end, int k) {
if (end - start < k) return 0; // Base case: not enough length to meet k requirementint[] freq =newint[26];
for (int i = start; i < end; i++) {
freq[s.charAt(i) -'a']++;
}
for (int i = start; i < end; i++) {
if (freq[s.charAt(i) -'a']< k) {
int j = i + 1;
while (j < end && freq[s.charAt(j) -'a']< k) j++;
return Math.max(longestSubstringHelper(s, start, i, k), longestSubstringHelper(s, j, end, k));
}
}
return end - start; // All characters in this range meet the k requirement }
}
classSolution:
deflongestSubstring(self, s: str, k: int) -> int:
return self._longestSubstring(s, 0, len(s), k)
def_longestSubstring(self, s: str, start: int, end: int, k: int) -> int:
if end - start < k:
return0# Base case: not enough length to meet k requirement freq = [0] *26for i in range(start, end):
freq[ord(s[i]) - ord('a')] +=1for i in range(start, end):
if freq[ord(s[i]) - ord('a')] < k:
j = i +1while j < end and freq[ord(s[j]) - ord('a')] < k:
j +=1return max(self._longestSubstring(s, start, i, k), self._longestSubstring(s, j, end, k))
return end - start # All characters in this range meet the k requirement
Time: O(n*n) , which is O(n^2) because each recursive call processes a substring and can make further recursive calls proportional to the length of the substring.