
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Permutation Sequence in C++
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[0] := 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
#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[0] = 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
- Related Articles
- Next Permutation in Python
- Find Permutation in C++
- Permutation in String in C++
- Permutation and Combination in Java
- Lexicographically next permutation in C++
- Permutation and Combination in Python?
- Letter Case Permutation in C++
- Palindrome Permutation II in C++
- Count Vowels Permutation in C++
- What is Initial Permutation in DES?
- Circular Permutation in Binary Representation in C++
- Alexander Bogomolny’s UnOrdered Permutation Algorithm in C++
- Previous Permutation With One Swap in Python
- What is Expansion Permutation in Information Security?
- How to calculate combination and permutation in C++?

Advertisements