Find the k th permutation
Problem to find the K th permutation value. First Line contain Integer N and 1<=N<=9.
If N = 3 the permutation are,
- 123
- 132
- 213
- 231
- 312
- 321
Example-1:
Input : N = 3 , K = 3 Output : "213"
Example-2:
Input : N = 3 , K = 4 Output : "231"
Example-3:
Input : N = 4 , K = 18 Output : "3421"
Solution
class Solution { public String getPermutation(int n, int k) { String str = ""; String ans = ""; for(int i = 1; i <= n; i++){ str = str + i; } return solve(ans,str,k); } public String solve(String ans,String str,int k) { int choice_digit = number_of_choice(str.length()); int temp = 0; for (int i = 0; i <str.length();i++) { if((i+1)*choice_digit >= k){ ans = ans + str.charAt(i); temp = i; break; } } str = str.substring(0,temp) + str.substring(temp+1,str.length()); if(str.length() != 0) { k = k % choice_digit; if(k==0) { k = choice_digit; } return solve(ans,str,k); } else { return ans; } } public int number_of_choice(int num) { int fact = 1; for (int i = 1; i <= num;i++){ fact = fact*i; } return fact/num; } } public class Main { public static void main(String[] args) { Solution obj = new Solution(); System.out.println(obj.getPermutation(4,18)); } }
from itertools import permutations n = 4 k = 18 a = "" for i in range(1,n+1): a += str(i) d = list(permutations(a,len(a))) print("".join(d[k-1]))
Output
3421