Leetcode 395. Longest Substring with At Least K Repeating Characters
Given a string s
and an integer k
, you need to find the length of the longest substring of s
such that the frequency of each character in this substring is at least k
.
s
?s
is an empty string or if k
is greater than the length of s
?s
consists of lowercase English letters.s
can be up to 10^4.s
is empty or k
is greater than the length of s
, return 0.A divide and conquer approach can be effective for solving this problem since the longest valid substring must also satisfy the same property in each divided part of the string. Here’s the plan:
s
is less than k
, no substring can satisfy the condition. Return 0.s
.k
times because any substring containing this character can’t satisfy the requirement.s
at this pivot.s
will be the max length of valid substrings found from the recursive calls.public class Solution {
public int longestSubstring(String s, int k) {
if (s == null || s.length() == 0) {
return 0;
}
return longestSubstringHelper(s, k, 0, s.length());
}
private int longestSubstringHelper(String s, int k, int start, int end) {
if (end - start < k) {
return 0;
}
int[] freq = new int[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 leftSubstring = longestSubstringHelper(s, k, start, i);
int rightSubstring = longestSubstringHelper(s, k, i + 1, end);
return Math.max(leftSubstring, rightSubstring);
}
}
return end - start;
}
}
n
is the length of the string. The factor 26 comes from the frequency array used in each recursion level, and the log(n) factors in the recursive splits.k
.This approach provides a balance between efficiency and simplicity, adequately solving the problem for allowed constraints.
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?