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
using System ; class GFG { public static char [ ] lexo_small ( int n , int k ) { char [ ] arr = new char [ n ] ; int i ; for ( i = 0 ; i < n ; i ++ ) arr [ i ] = ' a ' ; for ( i = n - 1 ; i >= 0 ; i -- ) { k -= i ; if ( k >= 0 ) { if ( k >= 26 ) { arr [ i ] = ' z ' ; k -= 26 ; } else { arr [ i ] = ( char ) ( k + 97 - 1 ) ; k -= arr [ i ] - ' a ' + 1 ; } } else break ; k += i ; } return arr ; } public static void Main ( ) { int n = 5 , k = 42 ; char [ ] arr = lexo_small ( n , k ) ; Console . WriteLine ( new string ( arr ) ) ; } }