Lexicographically n | Function to print nth permutation using next_permute ( ) ; Sort the string in lexicographically ascending order ; Keep iterating until we reach nth position ; check for nth iteration ; print string after nth iteration ; next_permutation method implementation ; Driver Code
def nPermute ( string , n ) : NEW_LINE INDENT string = list ( string ) NEW_LINE new_string = [ ] NEW_LINE string . sort ( ) NEW_LINE j = 2 NEW_LINE while next_permutation ( string ) : NEW_LINE INDENT new_string = string NEW_LINE if j == n : NEW_LINE INDENT break NEW_LINE DEDENT j += 1 NEW_LINE DEDENT print ( ' ' . join ( new_string ) ) NEW_LINE DEDENT def next_permutation ( L ) : NEW_LINE INDENT n = len ( L ) NEW_LINE i = n - 2 NEW_LINE while i >= 0 and L [ i ] >= L [ i + 1 ] : NEW_LINE INDENT i -= 1 NEW_LINE DEDENT if i == - 1 : NEW_LINE INDENT return False NEW_LINE DEDENT j = i + 1 NEW_LINE while j < n and L [ j ] > L [ i ] : NEW_LINE INDENT j += 1 NEW_LINE DEDENT j -= 1 NEW_LINE L [ i ] , L [ j ] = L [ j ] , L [ i ] NEW_LINE left = i + 1 NEW_LINE right = n - 1 NEW_LINE while left < right : NEW_LINE INDENT L [ left ] , L [ right ] = L [ right ] , L [ left ] NEW_LINE left += 1 NEW_LINE right -= 1 NEW_LINE DEDENT return True NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT string = " GEEKSFORGEEKS " NEW_LINE n = 100 NEW_LINE nPermute ( string , n ) NEW_LINE DEDENT