Open In App

Find the K-th Permutation Sequence of first N natural numbers

Improve
Improve
Like Article
Like
Save
Share
Report

Given two integers N and K, find the Kth permutation sequence of numbers from 1 to N without using STL function.
Note: Assume that the inputs are such that Kth permutation of N number is always possible.

Examples: 

Input: N = 3, K = 4 
Output: 231 
Explanation: 
The ordered list of permutation sequence from integer 1 to 3 is : 123, 132, 213, 231, 312, 321. So, the 4th permutation sequence is “231”.

Input: N = 2, K = 1 
Output: 12 
Explanation: 
For n = 2, only 2 permutations are possible 12 21. So, the 1st permutation sequence is “12”. 

Naive Approach:
To solve the problem mentioned above the simple approach is to find all permutation sequences and output the kth out of them. But this method is not so efficient and takes more time, hence it can be optimized.

C++




// C++ program to Find the kth Permutation
// Sequence of first n natural numbers
#include <bits/stdc++.h>
using namespace std;
 
// recursive function to generate all
// possible permutations of a string
void generate_permutations(string& str, int idx, vector<string>& result) {
    // base case
    if (idx == str.size()) {
        result.push_back(str);
        return;
    }
     
    // traverse string from idx to end
    for (int i = idx; i < str.size(); i++) {
        swap(str[i], str[idx]);
        generate_permutations(str, idx + 1, result);
        swap(str[i], str[idx]);
    }
}
 
// Function to find the
// kth permutation of n numbers
string findKthPermutation(int n, int k) {
    string str = "";
    vector<string> result;
     
    // Insert all natural number
    // upto n in string
    for (int i = 1; i <= n; i++) {
        str.push_back(i + '0');
    }
     
    generate_permutations(str, 0, result);
    // sort the generated permutations
    sort(result.begin(), result.end());
     
    // make k 0-based indexed to point to kth sequence
   return result[k-1];
}
 
// Driver code
int main() {
    int n = 3, k = 4;
     
    // function call
    string kth_perm_seq = findKthPermutation(n, k);
    cout << kth_perm_seq << endl;
 
    return 0;
}
 
// This code is contributed by Tapesh(tapeshdua420)


Java




// Java program to Find the kth Permutation
// Sequence of first n natural numbers
import java.util.*;
 
class GFG {
    // Driver code
    public static void main(String[] args)
    {
        int n = 3, k = 4;
        String kth_perm_seq = findKthPermutation(n, k);
 
        // function call
        System.out.println(kth_perm_seq);
    }
 
    static char[] swap(String s, int i, int j)
    {
        char[] ch = s.toCharArray();
        char temp = ch[i];
        ch[i] = ch[j];
        ch[j] = temp;
        return ch;
    }
 
    // recursive function to generate all
    // possible permutations of a string
    static void generate_permutations(String str, int idx,
                                      List<String> result)
    {
        // base case
        if (idx == str.length()) {
            result.add(str);
            return;
        }
 
        // traverse string from idx to end
        for (int i = idx; i < str.length(); i++) {
            str = new String(swap(str, i, idx));
            generate_permutations(str, idx + 1, result);
            str = new String(swap(str, i, idx));
        }
    }
 
    // Function to find the
    // kth permutation of n numbers
    static String findKthPermutation(int n, int k)
    {
        String str = "";
        List<String> result = new ArrayList<String>();
 
        // Insert all natural number
        // upto n in string
        for (int i = 1; i <= n; i++) {
            str += i;
        }
        generate_permutations(str, 0, result);
 
        // sort the generated permutations
        Collections.sort(result);
 
        // make k 0-based indexed to point to kth sequence
        return result.get(k - 1);
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Python3




# Python program to Find the kth Permutation
# Sequence of first n natural numbers
 
# recursive function to generate all
# possible permutations of a string
def generate_permutations(ch, idx, result):
    # base case
    if idx == len(ch):
        str1 = ""
        result.append(str1.join(ch))
        return
 
    # traverse string from idx to end
    for i in range(idx, len(ch)):
        ch[i], ch[idx] = ch[idx], ch[i]
        generate_permutations(ch, idx + 1, result)
        ch[i], ch[idx] = ch[idx], ch[i]
 
# Function to find the
# kth permutation of n numbers
def findKthPermutation(n, k):
    s = ""
    result = []
 
    # Insert all natural number
    # upto n in string
    for i in range(1, n + 1):
        s += str(i)
 
    ch = [*s]
    generate_permutations(ch, 0, result)
 
    # sort the generated permutations
    result.sort()
 
    # make k 0-based indexed to point to kth sequence
    return result[k - 1]
 
 
# Driver code
if __name__ == "__main__":
    n = 3
    k = 4
 
    # function call
    kth_perm_seq = findKthPermutation(n, k)
    print(kth_perm_seq)
 
# This code is contributed by Tapesh(tapeshdua420)


C#




// C# program to Find the kth Permutation
// Sequence of first n natural numbers
using System;
using System.Collections.Generic;
 
class Program {
    // Driver code
    static void Main(string[] args)
    {
        int n = 3, k = 4;
        string kth_perm_seq = findKthPermutation(n, k);
 
        // function call
        Console.WriteLine(kth_perm_seq);
    }
 
    static char[] swap(string s, int i, int j)
    {
        char[] ch = s.ToCharArray();
        char temp = ch[i];
        ch[i] = ch[j];
        ch[j] = temp;
        return ch;
    }
 
    // recursive function to generate all
    // possible permutations of a string
    static void generate_permutations(string str, int idx,
                                      List<string> result)
    {
        // base case
        if (idx == str.Length) {
            result.Add(str);
            return;
        }
 
        // traverse string from idx to end
        for (int i = idx; i < str.Length; i++) {
            str = new string(swap(str, i, idx));
            generate_permutations(str, idx + 1, result);
            str = new string(swap(str, i, idx));
        }
    }
 
    // Function to find the
    // kth permutation of n numbers
    static string findKthPermutation(int n, int k)
    {
        string str = "";
        List<string> result = new List<string>();
 
        // Insert all natural number
        // upto n in string
        for (int i = 1; i <= n; i++) {
            str += i;
        }
        generate_permutations(str, 0, result);
 
        // sort the generated permutations
        result.Sort();
 
        // make k 0-based indexed to point to kth sequence
        return result[k - 1];
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Javascript




<script>
  // JavaScript program to Find the kth Permutation
  // Sequence of first n natural numbers
 
  function swap(ch, i, j) {
      var temp = ch[i];
      ch[i] = ch[j];
      ch[j] = temp;
      return ch;
  }
 
  // recursive function to generate all
  // possible permutations of a string
  function generate_permutations(ch, idx, result) {
      // base case
      if (idx == ch.length) {
          result.push(ch.join(""));
          return;
      }
 
      // traverse string from idx to end
      for (var i = idx; i < ch.length; i++) {
          swap(ch, i, idx);
          generate_permutations(ch, idx + 1, result);
          swap(ch, i, idx);
      }
  }
 
  // Function to find the
  // kth permutation of n numbers
  function findKthPermutation(n, k) {
      var s = "";
      var result = [];
 
      // Insert all natural number
      // upto n in string
      for (var i = 1; i <= n; i++) {
          s += i;
      }
 
      var ch = s.split("");
      generate_permutations(ch, 0, result);
 
      // sort the gen
      // generated permutations
      result.sort();
 
      // make k 0-based indexed to point to kth sequence
      return result[k - 1];
  }
 
  // Driver code
 
  var n = 3;
  var k = 4;
 
  // function call
  var kth_perm_seq = findKthPermutation(n, k);
  console.log(kth_perm_seq);
 
 
  // This code is contributed by Tapesh(tapeshdua420)
 
</script>


Output

231






Time Complexity = O((N! * N) + (N! * log N!)) 
Auxiliary Space = O(N) to store all permutations

Efficient Approach:
To optimize the above method mentioned above, observe that the value of k can be directly used to find the number at each index of the sequence.  

  • The first position of an n length sequence is occupied by each of the numbers from 1 to n exactly n! / n that is (n-1)! number of times and in ascending order. So the first position of the kth sequence will be occupied by the number present at index = k / (n-1)! (according to 1-based indexing).
  • The currently found number can not occur again so it is removed from the original n numbers and now the problem reduces to finding the ( k % (n-1)! )th permutation sequence of the remaining n-1 numbers.
  • This process can be repeated until we have only one number left which will be placed in the first position of the last 1-length sequence.
  • The factorial values involved here can be very large as compared to k. So, the trick used to avoid the full computation of such large factorials is that as soon as the product n * (n-1) * … becomes greater than k, we no longer need to find the actual factorial value because: 

k / n_actual_factorial_value = 0 
and k / n_partial_factorial_value = 0 
when partial_factorial_value > k 
 

Below is the implementation of the above approach: 

C++




// C++ program to Find the kth Permutation
// Sequence of first n natural numbers
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the index of number
// at first position of
// kth sequence of set of size n
int findFirstNumIndex(int& k, int n)
{
 
    if (n == 1)
        return 0;
    n--;
 
    int first_num_index;
    // n_actual_fact = n!
    int n_partial_fact = n;
 
    while (k >= n_partial_fact
           && n > 1) {
        n_partial_fact
            = n_partial_fact
              * (n - 1);
        n--;
    }
 
    // First position of the
    // kth sequence will be
    // occupied by the number present
    // at index = k / (n-1)!
    first_num_index = k / n_partial_fact;
 
    k = k % n_partial_fact;
 
    return first_num_index;
}
 
// Function to find the
// kth permutation of n numbers
string findKthPermutation(int n, int k)
{
    // Store final answer
    string ans = "";
 
    set<int> s;
 
    // Insert all natural number
    // upto n in set
    for (int i = 1; i <= n; i++)
        s.insert(i);
 
    set<int>::iterator itr;
 
    // Mark the first position
    itr = s.begin();
 
    // subtract 1 to get 0 based indexing
    k = k - 1;
 
    for (int i = 0; i < n; i++) {
 
        int index
            = findFirstNumIndex(k, n - i);
 
        advance(itr, index);
 
        // itr now points to the
        // number at index in set s
        ans += (to_string(*itr));
 
        // remove current number from the set
        s.erase(itr);
 
        itr = s.begin();
    }
    return ans;
}
 
// Driver code
int main()
{
 
    int n = 3, k = 4;
 
    string kth_perm_seq
        = findKthPermutation(n, k);
 
    cout << kth_perm_seq << endl;
 
    return 0;
}


Java




// Java program to Find
// the kth Permutation
// Sequence of first
// n natural numbers
import java.util.*;
class GFG{
 
// Function to find the index of
// number at first position of
// kth sequence of set of size n
static int findFirstNumIndex(int k,
                             int n)
{
  if (n == 1)
    return 0;
  n--;
 
  int first_num_index;
   
  // n_actual_fact = n!
  int n_partial_fact = n;
 
  while (k >= n_partial_fact && n > 1)
  {
    n_partial_fact = n_partial_fact *
                     (n - 1);
    n--;
  }
 
  // First position of the
  // kth sequence will be
  // occupied by the number present
  // at index = k / (n-1)!
  first_num_index = k / n_partial_fact;
 
  k = k % n_partial_fact;
  return first_num_index;
}
 
// Function to find the
// kth permutation of n numbers
static String findKthPermutation(int n,
                                 int k)
{
  // Store final answer
  String ans = "";
 
  HashSet<Integer> s = new HashSet<>();
 
  // Insert all natural number
  // upto n in set
  for (int i = 1; i <= n; i++)
    s.add(i);
 
  Vector<Integer> v = new Vector<>();
  v.addAll(s);
 
  // Mark the first position
  int itr = v.elementAt(0);
   
  // Subtract 1 to
  // get 0 based
  // indexing
  k = k - 1;
 
  for (int i = 0; i < n; i++)
  {
    int index = findFirstNumIndex(k,
                                  n - i);
     
    // itr now points to the
    // number at index in set s
    if(index < v.size())
    {
      ans += ((v.elementAt(index).toString()));
      v.remove(index);
    }
    else
      ans += String.valueOf(itr + 2);
 
    // Remove current number
    // from the set
    itr = v.elementAt(0);
  }
  return ans;
}
 
// Driver code
public static void main(String[] args)
{
  int n = 3, k = 4;
  String kth_perm_seq = findKthPermutation(n, k);
  System.out.print(kth_perm_seq + "\n");
}
}
 
// This code is contributed by Rajput-Ji


Python3




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


C#




// C# program to Find
// the kth Permutation
// Sequence of first
// n natural numbers
using System;
using System.Collections.Generic;
class GFG{
 
// Function to find the index of
// number at first position of
// kth sequence of set of size n
static int findFirstNumIndex(int k,
                             int n)
{
  if (n == 1)
    return 0;
  n--;
 
  int first_num_index;
 
  // n_actual_fact = n!
  int n_partial_fact = n;
 
  while (k >= n_partial_fact && n > 1)
  {
    n_partial_fact = n_partial_fact *
                     (n - 1);
    n--;
  }
 
  // First position of the
  // kth sequence will be
  // occupied by the number present
  // at index = k / (n-1)!
  first_num_index = k / n_partial_fact;
 
  k = k % n_partial_fact;
  return first_num_index;
}
 
// Function to find the
// kth permutation of n numbers
static String findKthPermutation(int n,
                                 int k)
{
  // Store readonly answer
  String ans = "";
 
  HashSet<int> s = new HashSet<int>();
 
  // Insert all natural number
  // upto n in set
  for (int i = 1; i <= n; i++)
    s.Add(i);
 
  List<int> v = new List<int>(s);
 
  // Mark the first position
  int itr = v[0];
 
  // Subtract 1 to
  // get 0 based
  // indexing
  k = k - 1;
 
  for (int i = 0; i < n; i++)
  {
    int index = findFirstNumIndex(k, n - i);
 
    // itr now points to the
    // number at index in set s
    if(index < v.Count)
    {
      ans += ((v[index].ToString()));
      v.RemoveAt(index);
    }
    else
      ans += String.Join("", itr + 2);
 
    // Remove current number
    // from the set
    itr = v[0];
  }
  return ans;
}
 
// Driver code
public static void Main(String[] args)
{
  int n = 3, k = 4;
  String kth_perm_seq = findKthPermutation(n, k);
  Console.Write(kth_perm_seq + "\n");
}
}
 
// This code is contributed by Rajput-Ji


Javascript




// JavaScript program to find the kth permutation
// Sequence of first n natural numbers
 
// Function to find the index of number
// at first position of kth sequence of
// set of size n
function findFirstNumIndex(k, n)
{
 
    if (n == 1)
        return [0, k]
         
    n -= 1
    let first_num_index = 0
     
    // n_actual_fact = n!
    let n_partial_fact = n
 
    while (k >= n_partial_fact && n > 1)
    {
        n_partial_fact = n_partial_fact * (n - 1)
        n -= 1
    }
 
    // First position of the kth sequence
    // will be occupied by the number present
    // at index = k / (n-1)!
    first_num_index = Math.floor(k / n_partial_fact)
 
    k = k % n_partial_fact
 
    return [first_num_index, k]
}
 
// Function to find the
// kth permutation of n numbers
function findKthPermutation(n, k)
{
    // Store final answer
    let ans = ""
 
    let s = new Set()
 
    // Insert all natural number
    // upto n in set
    for (let i = 1; i <= n; i++)
        s.add(i)
 
    // Subtract 1 to get 0 based indexing
    k = k - 1
     
    for (let i = 0; i <n; i++)
    {
        // Mark the first position
        let itr = Array.from(s)
         
        let res =  findFirstNumIndex(k, n - i)
        let index = res[0]
        k = res[1]
         
         
        // itr now points to the
        // number at index in set s
        ans += (itr[index])
 
        // remove current number from the set
        itr.splice(index, 1)
         
        s = new Set(itr)
    }
    return ans
}
 
// Driver code
let n = 3
let k = 4
     
let kth_perm_seq = findKthPermutation(n, k)
 
console.log(kth_perm_seq)
 
// This code is contributed by phasing17


Output

231






Time Complexity : O(N^2) 
Auxiliary Space : O(N) 

Most Efficient Approach Using Combinatorics:

The base idea is that the first character can be found knowing that it has repeated (n-1)! times, given a particular value of n.

For example, given the base case “1234” with n = 4, we can list out all the permutations that starts with ‘1’:

1234
1324
1342
1243
1423
1432
As we can see, there are 6 cases in total where we have n = 4 that starts with ‘1’. That is because there are exactly (n-1)! = (4-1)! = 3! = 6 unique cases with the characters after the first one.

With this knowledge, we can deal with the problem recursively:

Given a particular value of n, and k, we can compute the first character in the set (i.e., {1,2,3,4,…,n}) of characters in increasing order by:

pos = k / factorial(n-1)
where pos is the index to the character in the set we want.

Then we have to remove the character at index pos from the set, since we can only use each character once.

What about the next iteration? Now that we have the desired character for n, we can turn to n-1, since we have knocked one of the n characters down, so n-1 left to go.

But what about k? Well, since we have considered a total number of k * factorial(n-1) permutations, we are left with k %= factorial(n-1), and that is going to be our new k for the next iteration.

An example for this, back to our case of n=4 above, imagine we have input k = 21. Now, we have already established there are 6 unique cases for the remaining n-1 characters for EACH of the unique character for the first one:

Looking at first character:

1 … (6 permutations)
2 … (6 permutations)
3 … (6 permutations)
Figured out first character is ‘4’.
Figured out first character, moving onto second characters, we have already considered 18 cases, so left with k %= factorial(n-1) = 21 %= 6 = 3 left.

C++




// C++ program to Find the kth Permutation
// Sequence of first n natural numbers
 
#include <bits/stdc++.h>
using namespace std;
 
// Function to find the index of number
// at first position of
// kth sequence of set of size n
// percalculated factorials
    int fact[10] = {1,1,2,6,24,120,720,5040,40320,362880};
     
    // recursively insert numbers in to string
    void permutation(int n, int k, set<int>&nums, string &str)
    {
        // base case n==0 then no numbers to process
        if(n==0) return;
         
        int val;
         
        // base case k=1 then add numbers from begin
        // base case k=0 then next numbers to be added will be in reverse from rbegin
        // k<=fact[n-1] then add the begin number
        if(k<=1 || k<=fact[n-1])
        {
            val = k==0 ? *nums.rbegin() : *nums.begin(); 
        }
        else
        {
            // calculate number of values cover k => k/fact[n-1]
            // so next value index => k/fact[n-1]
            int index = k/fact[n-1];               
            k = k %fact[n-1];   // remaining permutations
 
            // also if k%fact[n-1] == 0 then kth permutation covered by value is in index-1
            // EX: [2,3] n=2, k=2 => index  = k/fact[n-1] = 2/1 = 2
            // as k%fact[n-1] => 2%1 = 0, so decrease index to 1
            // so we take the value 3 as next value
 
            if(k==0)index--;
         
            // value taken
            val = *next(nums.begin(),index);
        }
         
        // add value to the string and remove from set
        str+= to_string(val); 
        nums.erase(val);
                 
        // decrement n in each step
        return permutation(n-1,k,nums,str);
    }
     
    string getPermutation(int n, int k) {
         
        // insert numbers 1 to N in to set
        set<int>nums;
        for(int i=1;i<=n;i++)nums.insert(i);
         
        // resulting string
        string str = "";
         
        permutation(n,k,nums,str);
         
        return str;
    }
 
// Driver code
int main()
{
 
    int n = 3, k = 4;
 
    string kth_perm_seq
        = getPermutation(n, k);
 
    cout << kth_perm_seq << endl;
 
    return 0;
}


Java




import java.util.TreeSet;
 
public class KthPermutation {
 
    // Function to find the kth permutation sequence of the first n natural numbers
    static int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
 
    // Recursively insert numbers into the string
    static void permutation(int n, int k, TreeSet<Integer> nums, StringBuilder str) {
        // Base case: n == 0, no numbers to process
        if (n == 0)
            return;
 
        int val;
 
        // Base case: k <= 1, add numbers from the beginning
        // Base case: k == 0, next numbers to be added will be in reverse order
        // k <= fact[n-1], then add the first number in the set
        if (k <= 1 || k <= fact[n - 1]) {
            val = (k == 0) ? nums.last() : nums.first();
        } else {
            // Calculate the number of values covered by k => k/fact[n-1]
            // So, the next value index => k/fact[n-1]
            int index = k / fact[n - 1];
            k = k % fact[n - 1];   // Remaining permutations
 
            // If k%fact[n-1] == 0, then the kth permutation is covered by the previous value
            // Decrease index by 1 in that case
            if (k == 0)
                index--;
 
            // Value taken for the next position
            val = (int) nums.toArray()[index];
        }
 
        // Add the value to the string and remove it from the set
        str.append(val);
        nums.remove(val);
 
        // Decrement n in each step
        permutation(n - 1, k, nums, str);
    }
 
    static String getPermutation(int n, int k) {
        // Insert numbers 1 to N into the TreeSet
        TreeSet<Integer> nums = new TreeSet<>();
        for (int i = 1; i <= n; i++)
            nums.add(i);
 
        // Resulting string
        StringBuilder str = new StringBuilder();
 
        permutation(n, k, nums, str);
 
        return str.toString();
    }
 
    // Driver code
    public static void main(String[] args) {
        int n = 3, k = 4;
 
        String kth_perm_seq = getPermutation(n, k);
 
        System.out.println(kth_perm_seq);
    }
}


Python3




# Python3 program to Find the kth Permutation
# Sequence of first n natural numbers
 
 
# Function to find the index of number
# at the first position of
# the kth sequence of the set of size n
# precalculated factorials
fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
 
# recursively insert numbers into the string
def permutation(n, k, nums, result_str):
    # base case n==0 then no numbers to process
    if n == 0:
        return result_str
 
    # base case k=1 then add numbers from the beginning
    # base case k=0 then next numbers to be added will be in reverse from rbegin
    # k<=fact[n-1] then add the beginning number
    if k <= 1 or k <= fact[n - 1]:
        val = nums[-1] if k == 0 else nums[0]
    else:
        # calculate the number of values that cover k => k/fact[n-1]
        # so the next value index => k/fact[n-1]
        index = k // fact[n - 1]
        k = k % fact[n - 1# remaining permutations
 
        # also if k%fact[n-1] == 0 then the kth permutation covered by value is in index-1
        # EX: [2,3] n=2, k=2 => index = k/fact[n-1] = 2/1 = 2
        # as k%fact[n-1] => 2%1 = 0, so decrease index to 1
        # so we take the value 3 as the next value
        if k == 0:
            index -= 1
 
        # value taken
        val = nums[index]
 
    # add the value to the string and remove it from the list
    result_str += str(val)
    nums.remove(val)
 
    # decrement n in each step
    return permutation(n - 1, k, nums, result_str)
 
def get_permutation(n, k):
    # insert numbers 1 to N into a list
    nums = list(range(1, n + 1))
 
    # resulting string
    result_str = ""
 
    return permutation(n, k, nums, result_str)
 
 
# Driver code
if __name__ == "__main__":
    n = 3
    k = 4
 
    kth_perm_seq = get_permutation(n, k)
 
    print(kth_perm_seq)


C#




using System;
using System.Linq;
using System.Collections.Generic;
 
public class KthPermutation
{
    // Function to find the kth permutation sequence of the first n natural numbers
    static int[] fact = { 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 };
 
    // Recursively insert numbers into the string
    static void Permutation(int n, int k, SortedSet<int> nums, System.Text.StringBuilder str)
    {
        // Base case: n == 0, no numbers to process
        if (n == 0)
            return;
 
        int val;
 
        // Base case: k <= 1, add numbers from the beginning
        // Base case: k == 0, next numbers to be added will be in reverse order
        // k <= fact[n-1], then add the first number in the set
        if (k <= 1 || k <= fact[n - 1])
        {
            val = (k == 0) ? nums.Max : nums.Min;
        }
        else
        {
            // Calculate the number of values covered by k => k/fact[n-1]
            // So, the next value index => k/fact[n-1]
            int index = k / fact[n - 1];
            k = k % fact[n - 1];   // Remaining permutations
 
            // If k%fact[n-1] == 0, then the kth permutation is covered by the previous value
            // Decrease index by 1 in that case
            if (k == 0)
                index--;
 
            // Value taken for the next position
            val = nums.ToArray()[index];
        }
 
        // Add the value to the string and remove it from the set
        str.Append(val);
        nums.Remove(val);
 
        // Decrement n in each step
        Permutation(n - 1, k, nums, str);
    }
 
    static string GetPermutation(int n, int k)
    {
        // Insert numbers 1 to N into the SortedSet
        SortedSet<int> nums = new SortedSet<int>();
        for (int i = 1; i <= n; i++)
            nums.Add(i);
 
        // Resulting string
        System.Text.StringBuilder str = new System.Text.StringBuilder();
 
        Permutation(n, k, nums, str);
 
        return str.ToString();
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int n = 3, k = 4;
 
        string kth_perm_seq = GetPermutation(n, k);
 
        Console.WriteLine(kth_perm_seq);
    }
}
 
 
// by phasing17


Javascript




// Function to find the kth permutation sequence of the first n natural numbers
const fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880];
 
// Recursively insert numbers into the string
function permutation(n, k, nums, str) {
    // Base case: n == 0, no numbers to process
    if (n === 0) {
        return;
    }
 
    let val;
 
    // Base case: k <= 1, add numbers from the beginning
    // Base case: k == 0, next numbers to be added will be in reverse order
    // k <= fact[n-1], then add the first number in the set
    if (k <= 1 || k <= fact[n - 1]) {
        val = (k === 0) ? [...nums][nums.size - 1] : [...nums][0];
    } else {
        // Calculate the number of values covered by k => k/fact[n-1]
        // So, the next value index => k/fact[n-1]
        const index = Math.floor(k / fact[n - 1]);
        k = k % fact[n - 1];   // Remaining permutations
 
        // If k%fact[n-1] === 0, then the kth permutation is covered by the previous value
        // Decrease index by 1 in that case
        if (k === 0) {
            val = [...nums][index - 1];
        } else {
            // Value taken for the next position
            val = [...nums][index];
        }
    }
 
    // Add the value to the string and remove it from the set
    str.push(val);
    nums.delete(val);
 
    // Decrement n in each step
    permutation(n - 1, k, nums, str);
}
 
function getPermutation(n, k) {
    // Insert numbers 1 to N into a Set
    const nums = new Set();
    for (let i = 1; i <= n; i++) {
        nums.add(i);
    }
 
    // Resulting string
    const str = [];
 
    permutation(n, k, nums, str);
 
    return str.join('');
}
 
// Driver code
const n = 3, k = 4;
 
const kth_perm_seq = getPermutation(n, k);
 
console.log(kth_perm_seq);
 
 
// This code is contributed by shivamgupta310570


Output:

231

Time Complexity : O(N) for generating all the permutations and traversals.
Auxiliary Space : O(N) for storing all permutation.



Last Updated : 02 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads