Longest sub | JavaScript implementation to find the length of the longest substring having frequency of each character less than equal to k ; function to find the length of the longest substring having frequency of each character less than equal to k ; hash table to store frequency of each table ; ' start ' index of the current substring ; to store the maximum length ; traverse the string ' str ' ; get the current character as ' ch ' ; increase frequency of ' ch ' in ' freq [ ] ' ; if frequency of ' ch ' becomes more than ' k ' ; update ' maxLen ' ; decrease frequency of each character as they are encountered from the ' start ' index until frequency of ' ch ' is greater than ' k ' ; decrement frequency by '1' ; increment ' start ' ; update maxLen ; required length ; Driver program to test above
var SIZE = 26 ; function longSubstring ( str , k ) { var freq = Array ( SIZE ) . fill ( 0 ) ; var start = 0 ; var maxLen = 0 ; var ch ; var n = str . length ; for ( var i = 0 ; i < n ; i ++ ) { ch = str [ i ] ; freq [ ch . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; if ( freq [ ch . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] > k ) { if ( maxLen < ( i - start ) ) maxLen = i - start ; while ( freq [ ch . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] > k ) { freq [ str [ start ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] -- ; start ++ ; } } } if ( maxLen < ( n - start ) ) maxLen = n - start ; return maxLen ; } var str = " " ; var k = 1 ; document . write ( " " + longSubstring ( str , k ) ) ;