Lexicographically next greater string using same character set | 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 ; 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
def lexoString ( s , k ) : NEW_LINE INDENT n = len ( s ) NEW_LINE v = [ ] NEW_LINE mp = { s [ i ] : 0 for i in range ( len ( s ) ) } NEW_LINE for i in range ( len ( s ) ) : NEW_LINE INDENT if ( mp [ s [ i ] ] == 0 ) : NEW_LINE INDENT mp [ s [ i ] ] = 1 NEW_LINE v . append ( s [ i ] ) NEW_LINE DEDENT DEDENT v . sort ( reverse = False ) NEW_LINE if ( k > n ) : NEW_LINE INDENT print ( s , end = " " ) NEW_LINE for i in range ( n , k , 1 ) : NEW_LINE INDENT print ( v [ 0 ] , end = " " ) NEW_LINE DEDENT return ; NEW_LINE DEDENT i = k - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( s [ i ] != v [ len ( v ) - 1 ] ) : NEW_LINE INDENT for j in range ( 0 , i , 1 ) : NEW_LINE INDENT print ( s [ j ] , end = " ▁ " ) NEW_LINE DEDENT for j in range ( 0 , len ( v ) , 1 ) : NEW_LINE INDENT if ( v [ j ] > s [ i ] ) : NEW_LINE INDENT print ( v [ j ] , end = " ▁ " ) NEW_LINE break NEW_LINE DEDENT DEDENT for j in range ( i + 1 , k , 1 ) : NEW_LINE INDENT print ( v [ 0 ] , end = " ▁ " ) NEW_LINE DEDENT re1turn NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT print ( " No ▁ lexicographically ▁ greater " , " string ▁ of ▁ length " , k , " possible ▁ here . " ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT s = " gi " NEW_LINE k = 3 NEW_LINE lexoString ( s , k ) NEW_LINE DEDENT