# Permutation Sequence in C++

C++Server Side ProgrammingProgramming

Suppose the set is like [1,2,3,...,n], contains a total of n! unique permutations. By listing and labeling all of the permutations in order, we get these sequence for n = 3: ["123","132","213","231","312","321"] So if n and k are given, then return the kth permutation sequence. The n will be between 1 to 9 (inclusive) and k will be between 1 to n! (inclusive). For example if n = 3.

Let us see the steps −

• ans := empty string, define array called candidates of size n
• for i in range 0 to n – 1
• candidates[i] := ((i + 1) + character ‘0’)
• create one array called fact of size n + 1, set fact := 1
• for i in range 1 to n
• fact[i] := fact[i – 1] * i
• decrease k by 1
• for i := n – 1 down to 0
• idx := k / fact[i]
• ans := ans + candidates[idx]
• for j := idx, j + 1 < size of candidates
• candidates[j] := candidates[j + 1]
• k := k mod fact[i]
• return ans

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
string getPermutation(int n, int k) {
string ans = "";
vector <char> candidates(n);
for(lli i = 0; i < n; i++)
candidates[i] = ((i + 1) + '0');
vector <lli> fact(n + 1);
fact = 1;
for(lli i = 1; i <= n; i++)
fact[i] = fact[i - 1] * i;
k--;
for(lli i = n - 1; i >= 0; i--){
lli idx = k / fact[i];
ans += candidates[idx];
for(lli j = idx; j + 1< candidates.size(); j++)
candidates[j] = candidates[j + 1];
k = k % fact[i];
}
return ans;
}
};
main(){
Solution ob;
cout << ob.getPermutation(4, 9);
}

## Input

4
9

## Output

2314