Largest sub | C ++ implementation of the approach ; Function that return true if frequency of all the present characters is at least k ; If the character is present and its frequency is less than k ; Function to set every frequency to zero ; Function to return the length of the longest sub - string such that it contains every character at least k times ; To store the required maximum length ; Starting index of the sub - string ; Ending index of the sub - string ; If the frequency of every character of the current sub - string is at least k ; Update the maximum possible length ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  26 NEW_LINE bool atLeastK ( int freq [ ] , int k ) { for ( int i = 0 ; i < MAX ; i ++ ) { if ( freq [ i ] != 0 && freq [ i ] < k ) return false ; } return true ; } void setZero ( int freq [ ] ) { for ( int i = 0 ; i < MAX ; i ++ ) freq [ i ] = 0 ; } int findlength ( string str , int n , int k ) { int maxLen = 0 ; int freq [ MAX ] ; for ( int i = 0 ; i < n ; i ++ ) { setZero ( freq ) ; for ( int j = i ; j < n ; j ++ ) { freq [ str [ j ] - ' a ' ] ++ ; if ( atLeastK ( freq , k ) ) { maxLen = max ( maxLen , j - i + 1 ) ; } } } return maxLen ; } int main ( ) { string str = " xyxyyz " ; int n = str . length ( ) ; int k = 2 ; cout << findlength ( str , n , k ) ; return 0 ; }