Lexicographically next greater string using same character set | Java 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
import java . util . * ; class GFG { static void lexoString ( char [ ] s , int k ) { int n = s . length ; Vector < Character > v = new Vector < > ( ) ; Map < Character , Integer > mp = new HashMap < > ( ) ; for ( int i = 0 ; i < s . length ; i ++ ) { if ( ! mp . containsKey ( s [ i ] ) ) { mp . put ( s [ i ] , 1 ) ; v . add ( s [ i ] ) ; } } Collections . sort ( v ) ; if ( k > n ) { System . out . print ( String . valueOf ( s ) ) ; for ( int i = n ; i < k ; i ++ ) { System . out . print ( v . get ( 0 ) ) ; } } for ( int i = k - 1 ; i >= 0 ; i -- ) { if ( s [ i ] != v . get ( v . size ( ) - 1 ) ) { for ( int j = 0 ; j < i ; j ++ ) { System . out . print ( s [ j ] ) ; } for ( int j = 0 ; j < v . size ( ) ; j ++ ) { if ( v . get ( j ) > s [ i ] ) { System . out . print ( v . get ( j ) ) ; break ; } } for ( int j = i + 1 ; j < k ; j ++ ) { System . out . print ( v . get ( 0 ) ) ; } return ; } } System . out . print ( " 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 ) ; } }