Lexicographically smallest string of length N and sum K | C ++ implementation of the approach ; 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string lexo_small ( int n , int k ) { string arr = " " ; for ( int i = 0 ; i < n ; i ++ ) arr += ' a ' ; for ( int i = n - 1 ; i >= 0 ; i -- ) { k -= i ; if ( k >= 0 ) { if ( k >= 26 ) { arr [ i ] = ' z ' ; k -= 26 ; } else { char c = ( char ) ( k + 97 - 1 ) ; arr [ i ] = c ; k -= arr [ i ] - ' a ' + 1 ; } } else break ; k += i ; } return arr ; } int main ( ) { int n = 5 , k = 42 ; string arr = lexo_small ( n , k ) ; cout << arr ; }