Find the K | Function to find the index of number at first position of kth sequence of set of size n ; n_actual_fact = n ! ; First position of the kth sequence will be occupied by the number present at index = k / ( n - 1 ) ! ; Function to find the kth permutation of n numbers ; Store final answer ; Insert all natural number upto n in set ; Subtract 1 to get 0 based indexing ; Mark the first position ; itr now points to the number at index in set s ; remove current number from the set ; Driver code
def findFirstNumIndex ( k , n ) : NEW_LINE INDENT if ( n == 1 ) : NEW_LINE INDENT return 0 , k NEW_LINE DEDENT n -= 1 NEW_LINE first_num_index = 0 NEW_LINE n_partial_fact = n NEW_LINE while ( k >= n_partial_fact and n > 1 ) : NEW_LINE INDENT n_partial_fact = n_partial_fact * ( n - 1 ) NEW_LINE n -= 1 NEW_LINE DEDENT first_num_index = k // n_partial_fact NEW_LINE k = k % n_partial_fact NEW_LINE return first_num_index , k NEW_LINE DEDENT def findKthPermutation ( n , k ) : NEW_LINE INDENT ans = " " NEW_LINE s = set ( ) NEW_LINE for i in range ( 1 , n + 1 ) : NEW_LINE INDENT s . add ( i ) NEW_LINE DEDENT k = k - 1 NEW_LINE for i in range ( n ) : NEW_LINE INDENT itr = list ( s ) NEW_LINE index , k = findFirstNumIndex ( k , n - i ) NEW_LINE ans += str ( itr [ index ] ) NEW_LINE itr . pop ( index ) NEW_LINE s = set ( itr ) NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 3 NEW_LINE k = 4 NEW_LINE kth_perm_seq = findKthPermutation ( n , k ) NEW_LINE print ( kth_perm_seq ) NEW_LINE DEDENT