Home » Interview Questions » String Interview Questions » Permutations (STL)

Permutations (STL)


()

Print all the permutations of the input string using STL functions.

Example

Input string : “ABC”

Output : ABC, ACB, BAC, BCA, CAB, CBA

Time complexity : O(n)

Algorithm

Here we use next_permute() function, which rearranges the given string and return lexicographically next permutation.

a. We store the sorted string.

b. Until the function next_permutation() return false.

c. Print all permutations.

C++ Program

#include <bits/stdc++.h>

using namespace std;
 
void permutations(string str)
{
    sort(str.begin(), str.end());//Sort input string
    cout<<str<<endl;
    while (next_permutation(str.begin(), str.end()))
    {
        cout<<str<<endl;
    }  
}
//Main functions
int main()
{
    string str = "CBA";
    permutations(str);
    return 0;
}

Try It

 

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote Count

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

READ  Next Permutation
Array Interview Questions
Graph Interview Questions
LinkedList Interview Questions
String Interview Questions
Tree Interview Questions