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 to ; 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
def getLargestString ( s , k ) : NEW_LINE INDENT frequency_array = [ 0 ] * 26 NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT frequency_array [ ord ( s [ i ] ) - ord ( ' a ' ) ] += 1 NEW_LINE DEDENT ans = " " NEW_LINE i = 25 NEW_LINE while i >= 0 : NEW_LINE INDENT if ( frequency_array [ i ] > k ) : NEW_LINE INDENT temp = k NEW_LINE st = chr ( i + ord ( ' a ' ) ) NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT ans += st NEW_LINE temp -= 1 NEW_LINE DEDENT frequency_array [ i ] -= k NEW_LINE j = i - 1 NEW_LINE while ( frequency_array [ j ] <= 0 and j >= 0 ) : NEW_LINE INDENT j -= 1 NEW_LINE DEDENT if ( frequency_array [ j ] > 0 and j >= 0 ) : NEW_LINE INDENT str1 = chr ( j + ord ( ' a ' ) ) NEW_LINE ans += str1 NEW_LINE frequency_array [ j ] -= 1 NEW_LINE DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT elif ( frequency_array [ i ] > 0 ) : NEW_LINE INDENT temp = frequency_array [ i ] NEW_LINE frequency_array [ i ] -= temp NEW_LINE st = chr ( i + ord ( ' a ' ) ) NEW_LINE while ( temp > 0 ) : NEW_LINE INDENT ans += st NEW_LINE temp -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT S = " xxxxzza " NEW_LINE k = 3 NEW_LINE print ( getLargestString ( S , k ) ) NEW_LINE DEDENT