Find the K-th Permutation Sequence of first N natural numbers
Last Updated :
17 Apr, 2024
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>
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
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
public class KthPermutation {
static class TreeNode {
int val;
TreeNode left, right;
public TreeNode(int val) {
this.val = val;
this.left = this.right = null;
}
}
static int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
static TreeNode insert(TreeNode root, int val) {
if (root == null)
return new TreeNode(val);
if (val < root.val)
root.left = insert(root.left, val);
else
root.right = insert(root.right, val);
return root;
}
static TreeNode delete(TreeNode root, int val) {
if (root == null)
return null;
if (val < root.val)
root.left = delete(root.left, val);
else if (val > root.val)
root.right = delete(root.right, val);
else {
if (root.left == null)
return root.right;
else if (root.right == null)
return root.left;
root.val = minValue(root.right);
root.right = delete(root.right, root.val);
}
return root;
}
static int minValue(TreeNode root) {
int minv = root.val;
while (root.left != null) {
minv = root.left.val;
root = root.left;
}
return minv;
}
static int findKthSmallest(TreeNode root, int k) {
if (root == null)
return -1;
int leftCount = countNodes(root.left);
if (k == leftCount + 1)
return root.val;
if (k <= leftCount)
return findKthSmallest(root.left, k);
return findKthSmallest(root.right, k - leftCount - 1);
}
static int countNodes(TreeNode root) {
if (root == null)
return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
}
static String getPermutation(int n, int k) {
TreeNode root = null;
for (int i = 1; i <= n; i++)
root = insert(root, i);
StringBuilder str = new StringBuilder();
for (int i = 0; i < n; i++) {
int index = (k - 1) / fact[n - i - 1] + 1;
int val = findKthSmallest(root, index);
str.append(val);
root = delete(root, val);
k = k - (index - 1) * fact[n - i - 1];
}
return str.toString();
}
public static void main(String[] args) {
int n = 3, k = 4;
String kth_perm_seq = getPermutation(n, k);
System.out.println(kth_perm_seq); // Output: 231
}
}
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.
Similar Reads
Count unimodal and non-unimodal permutations of first N natural numbers
Given an integer N, the task is to count the total number of unimodal and non-unimodal permutations of integers [1, N] possible. An unimodal permutation is a permutation which increases up to a certain point following which it starts decreasing. All other permutations, excluding unimodal permutation
14 min read
Count array elements that can be maximized by adding any permutation of first N natural numbers
Given an array arr[] consisting of N integers, the task is to determine the total number of array elements that can become the maximum value in the array by adding any permutation of [1, N] to the corresponding value in the given array. Examples: Input: N = 3, arr[] = {8, 9, 6} Output: 2Explanation:
7 min read
Count of subarrays of size K which is a permutation of numbers from 1 to K
Given an array arr of distinct integers, the task is to find the count of sub-arrays of size i having all elements from 1 to i, in other words, the sub-array is any permutation of elements from 1 to i, with 1 < = i <= N. Examples: Input: arr[] = {2, 3, 1, 5, 4} Output: 3 Explanation: we have {
6 min read
Program to find sum of the given sequence
Given two numbers [Tex]N [/Tex]and . The task is to find the sum of the sequence given below. (1*2*3*...*k) + (2*3*...*k*(k+1)) + (3*4*..*(k+1)*(k+2)) +.....+((n-k+1)*(n-k+2)*...*(n-k+k)). Since the output can be large, print the answer under modulo 10^9+7.Examples: Input : N = 3, K = 2 Output : 8 I
7 min read
All reverse permutations of an array using STL in C++
Given an array, the task is to print or display all the reverse permutations of this array using STL in C++. Reverse permutation means, for an array {1, 2, 3}: forward permutations: 1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 reverse permutations: 3 2 1 3 1 2 2 3 1 2 1 3 1 3 2 1 2 3 Examples: Input: a[] = {
3 min read
Iterative program to generate distinct Permutations of a String
Given a string str, the task is to generate all the distinct permutations of the given string iteratively. Examples: Input: str = "bba" Output: abb bab bba Input: str = "abc" Output: abc acb bac bca cab cba Approach: The number of permutations for a string of length n are n!. The following algorithm
15+ min read
Product of all Subsequences of size K except the minimum and maximum Elements
Given an array A[] containing N elements and an integer K. The task is to calculate the product of all elements of subsequences of size K except the minimum and the maximum elements for each subsequence. Note: Since the answer can be very large so print the final answer as mod of 109 + 7. Examples:
12 min read
Generate all possible permutations of a Number divisible by N
Given a numerical string S, the task is to print all the permutations of the string which are divisible by N. Examples: Input: N = 5, S = "125" Output: 125 215Explanation: All possible permutations are S are {125, 152, 215, 251, 521, 512}. Out of these 6 permutations, only 2 {125, 215} are divisible
5 min read
Number of subsequences of maximum length K containing no repeated elements
Given an array arr[] of N elements and a positive integer K such that K ⤠N. The task is to find the number of subsequences of maximum length K i.e. subsequences of length 0, 1, 2, ..., K - 1, K that have all distinct elements. Examples: Input: arr[] = {2, 2, 3, 3, 5}, K = 2 Output: 14 All the valid
15 min read
Find All Permutations of an Array using STL in C++
The permutation of an array refers to a rearrangement of its elements in every possible order. In this article, we will learn how to generate all possible permutation of an array using STL in C++. The simplest method to find all the permutations of an array is to use next_permutation(). The array ha
2 min read