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 greater than or equal to k.

if no such substring exists, return 0.

Input: s = "aaabb", k = 3
Output: 3
Explanation: The longest substring is "aaa", as 'a' is repeated 3 times.
Input: s = "ababbc", k = 2
Output: 5
Explanation: The longest substring is "ababb", as 'a' is repeated 2 times and 'b' is repeated 3 times.
Constraints:

Contents

In this approach, we will first capture the characters frequency in input string s into an array of size 26 (each represents lowercase alphabet count). Then, we will find find where the breaks are in input string, i.e. if any charater appeared less than k times, this character cannot be part of substring and it breaks the string into to two substrings, then we repeat this process on two substrings in a recursive fashion and keep track of maximum length substring which has characters appeared atleast k times.

Let's understand with an example, say the input string is s = "ababbbcadd" and k=3

Problem 1a illustration

Implementation steps:
public class LongestSubstringWithAtleastKRepeatingChars { static int longestWithAtleasetKRepeating(String s, int k) { return helper(s, 0, s.length(), k); } static int helper(String s, int left, int right, int k) { if(right - left <k) { return 0; } int[] charsFrequency = new int[26]; for(int i=left; i<right; i++) { charsFrequency[s.charAt(i)-'a']++; } boolean isValid = true; int start =0; int result =0; for( int i=left; i<right; i++) { if(charsFrequency[s.charAt(i)-'a'] <k) { result = Math.max(result, helper(s, left, i, k)); isValid = false; start = i+1; // move to next position } } return isValid ? right - left : Math.max(result, helper(s, start, right, k)); } public static void main(String[] args) { System.out.println(longestWithAtleasetKRepeating("aaabb", 3)); } }
Complexity Analysis:

Time complexity: Above code runs in O(n) time, where n is the length of input string s.
Space complexity: O(n), space that will be used by recursive calls stack, since there can be n substrings.

Above implementations source code can be found at GitHub link for Java code