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
function lexo_small ( n , k ) { var arr = Array . from ( { length : n } , ( _ , i ) => ' ' ) ; for ( var i = n - 1 ; i >= 0 ; i -- ) { k -= i ; if ( k >= 0 ) { if ( k >= 26 ) { arr [ i ] = ' ' ; k -= 26 ; } else { arr [ i ] = String . fromCharCode ( k + 97 - 1 ) ; k -= arr [ i ] - ' ' + 1 ; } } else break ; k += i ; } return arr ; } var n = 5 , k = 42 ; var arr = lexo_small ( n , k ) ; document . write ( arr . join ( ' ' ) ) ;