Lexicographically smallest string of length N and sum K | Function to return the lexicographically smallest string of length n that satisfies the given condition ; Iteration from the last position in the array ; If k is a positive integer ; ' z ' needs to be inserted ; Add the required character ; Driver code
def lexo_small ( n , k ) : NEW_LINE INDENT arr = " " ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr += ' a ' ; NEW_LINE DEDENT for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT k -= i ; NEW_LINE if ( k >= 0 ) : NEW_LINE INDENT if ( k >= 26 ) : NEW_LINE INDENT arr = arr [ : i ] + ' z ' + arr [ i + 1 : ] ; NEW_LINE k -= 26 ; NEW_LINE DEDENT else : NEW_LINE INDENT c = ( k + 97 - 1 ) ; NEW_LINE arr = arr [ : i ] + chr ( c ) + arr [ i + 1 : ] ; NEW_LINE k -= ord ( arr [ i ] ) - ord ( ' a ' ) + 1 ; NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break ; NEW_LINE DEDENT k += i ; NEW_LINE DEDENT return arr ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 5 ; k = 42 ; NEW_LINE arr = lexo_small ( n , k ) ; NEW_LINE print ( arr ) ; NEW_LINE DEDENT