Largest lexicographical string with at most K consecutive elements | Function to find the largest lexicographical String with given constraints . ; Vector containing frequency of each character . ; Assigning frequency ; Empty String of String class type ; Loop to iterate over maximum priority first . ; If frequency is greater than or equal to k . ; Temporary variable to operate in - place of k . ; Concatenating with the resultant String ans . ; Handling k case by adjusting with just smaller priority element . ; Condition to verify if index j does have frequency greater than 0 ; ; If no such element is found than String can not be processed further . ; If frequency is greater than 0 and less than k . ; Here we don 't need to fix K  consecutive element criteria. ; Otherwise check for next possible element . ; Driver code
function getLargestString ( s , k ) { let frequency_array = new Array ( 26 ) ; for ( let i = 0 ; i < 26 ; i ++ ) { frequency_array [ i ] = 0 ; } for ( let i = 0 ; i < s . length ; i ++ ) { frequency_array [ s [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ] ++ ; } let ans = " " ; for ( let i = 25 ; i >= 0 ; ) { if ( frequency_array [ i ] > k ) { let temp = k ; let st = String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ; while ( temp > 0 ) { ans += st ; temp -- ; } frequency_array [ i ] -= k ; let j = i - 1 ; while ( frequency_array [ j ] <= 0 && j >= 0 ) { j -- ; } if ( frequency_array [ j ] > 0 && j >= 0 ) { let str = String . fromCharCode ( j + ' ' . charCodeAt ( 0 ) ) ; ans += str ; frequency_array [ j ] -= 1 ; } else { break ; } } else if ( frequency_array [ i ] > 0 ) { let temp = frequency_array [ i ] ; frequency_array [ i ] -= temp ; let st = String . fromCharCode ( i + ' ' . charCodeAt ( 0 ) ) ; while ( temp > 0 ) { ans += st ; temp -- ; } } else { i -- ; } } return ans ; } let S = " " ; let k = 3 ; document . write ( getLargestString ( S , k ) ) ;