[InterviewBit] Kth Permutation Sequence

Kth Permutation Sequence

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int fact(int n, int k) {
int res = 1;
for(int i = 1; i <= n and res <= k; i++) res *= i;
return res;
}
string helper(set<int>& s, int k) {
if(s.size() == 1) return to_string(*begin(s));
else {
int perm = s.size() - 1;
int fac = fact(perm,k);
int jump = k / fac;
int num = *next(s.begin(), jump);
s.erase(num);
return to_string(num) + helper(s,k-jump * fac);
}
}
string Solution::getPermutation(int A, int B) {
set<int> s;
for(int i = 1; i <= A; i++) s.insert(i);
return helper(s,B-1);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/21/PS/interviewbit/kth-permutation-sequence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.