Lexicographically n-th permutation of a string

Given a string of length m containing lowercase alphabets only. You have to find the n-th permutation of string lexicographically.


Input : str[] = "abc", n = 3
Output : Result = "bac"
Explanation : All possible permutation in
sorted order: abc, acb, bac, bca, cab, cba

Input : str[] = "aba", n = 2
Output : Result = "aba"
Explanation : All possible permutation
in sorted order: aab, aba, baa

Prerequisite : Permutations of a given string using STL

Idea behind printing n-th permutation is quite simple we should use STL (explained in above link) for finding next permutation and do it till the nth permutation. After n-th iteration, we should break from the loop and then print the string which is our nth permutation.

    long int i = 1;
        // check for nth iteration
        if (i == n)
       i++; // keep incrementing the iteration
    } while (next_permutation(str.begin(), str.end()));

    // print string after nth iteration
   print str;




// C++ program to print nth permutation with
// using next_permute()
#include <bits/stdc++.h>
using namespace std;
// Function to print nth permutation
// using next_permute()
void nPermute(string str, long int n)
    // Sort the string in lexicographically
    // ascending order
    sort(str.begin(), str.end());
    // Keep iterating until
    // we reach nth position
    long int i = 1;
    do {
        // check for nth iteration
        if (i == n)
    } while (next_permutation(str.begin(), str.end()));
    // print string after nth iteration
    cout << str;
// Driver code
int main()
    string str = "GEEKSFORGEEKS";
    long int n = 100;
    nPermute(str, n);
    return 0;




Find n-th lexicographically permutation of a string | Set 2

This article is contributed by Shivam Pradhan (anuj_charm). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.