Lexicographically next greater string using same character set | C # implementation of above algorithm . ; function to print output ; to store unique characters of the string ; to check uniqueness ; if mp [ s [ i ] ] = 0 then it is first time ; sort the unique characters ; simply add n - k smallest characters ; return ; end the program ; searching the first character left of index k and not equal to greatest character of the string ; finding the just next greater character than s [ i ] ; suffix with smallest character ; if we reach here then all indices to the left of k had the greatest character ; Driver code ; Function call
using System ; using System . Collections . Generic ; class GFG { static void lexoString ( char [ ] s , int k ) { int n = s . Length ; List < char > v = new List < char > ( ) ; Dictionary < char , int > mp = new Dictionary < char , int > ( ) ; for ( int i = 0 ; i < s . Length ; i ++ ) { if ( ! mp . ContainsKey ( s [ i ] ) ) { mp . Add ( s [ i ] , 1 ) ; v . Add ( s [ i ] ) ; } } v . Sort ( ) ; if ( k > n ) { Console . Write ( String . Join ( " " , s ) ) ; for ( int i = n ; i < k ; i ++ ) { Console . Write ( v [ 0 ] ) ; } } for ( int i = k - 1 ; i >= 0 ; i -- ) { if ( s [ i ] != v [ v . Count - 1 ] ) { for ( int j = 0 ; j < i ; j ++ ) { Console . Write ( s [ j ] ) ; } for ( int j = 0 ; j < v . Count ; j ++ ) { if ( v [ j ] > s [ i ] ) { Console . Write ( v [ j ] ) ; break ; } } for ( int j = i + 1 ; j < k ; j ++ ) { Console . Write ( v [ 0 ] ) ; } return ; } } Console . Write ( " No ▁ lexicographically ▁ greater ▁ " + " string ▁ of ▁ length ▁ " + k + " ▁ possible ▁ here . " ) ; } public static void Main ( String [ ] arr ) { String s = " gi " ; int k = 3 ; lexoString ( s . ToCharArray ( ) , k ) ; } }