Permutations of a given string using STL
Last Updated :
11 Feb, 2025
Given a string s, the task is to return all unique permutations of a given string in lexicographically sorted order.
Note: A permutation is the rearrangement of all the elements of a string.
Examples:
Input: s = "ABC"
Output: "ABC", "ACB", "BAC", "BCA", "CBA", "CAB"
Input: s = "XY"
Output: "XY", "YX"
Input: s = "AAA"
Output: "AAA"
Note: An approach using backtracking has already been discussed in Distinct Permutation of String. In this article two approaches using STL has been discussed.
Using Rotate() - O(n * n!) Time and O(n) Space
The idea is to generate all possible permutation of given string s using the rotate() function which rotates elements of string such that the passed middle element becomes first. To do so create an auxiliary string x and a HashSetres to store unique permutation in sorted order.
Start iterating from the first element and for each recursive call check if string s is empty, if so store the string x in res else recur again by removing the first element of string s and adding to last of string x. At last rotate the string s byremoving the first character from string s and appending it to the lastto generate the next permutation.
Note: For C++, rotate() stl is used, while for other languages, same operation has been done by removing the first character from string s and appending it to the last.

Below is given the implementation.
C++
// C++ Program to find permutation
// of string using rotate() function
#include <bits/stdc++.h>
using namespace std;
// Recursive Function to generate permutation
void recurPermute(string s, string x, set<string> &res) {
// if string s becomes empty, then
// we have permutation stored in x
if (s.size() == 0) {
// store the permutation in res
res.insert(x);
return;
}
// else iterate through the string
for (int i = 0; i < s.size(); i++) {
// remove the first character from
// string s and add to string x
recurPermute(s.substr(1), x + s[0], res);
// rotating such that second element becomes first
rotate(s.begin(), s.begin() + 1, s.end());
}
}
// Function to find all permutation of string
vector<string> findPermutation(string &s){
// to store all the permutations
set<string> res;
// call the recursive function
recurPermute(s, "", res);
// stores all unique permutation
vector<string> ans;
for(auto i:res){
ans.push_back(i);
}
return ans;
}
int main() {
string s = "ABC";
vector<string> ans = findPermutation(s);
for(auto i: ans){
cout << i << " ";
}
return 0;
}
OutputABC ACB BAC BCA CAB CBA
Time Complexity: O(n*n!)
Auxiliary Space: O(n)
Using next_permutation() Function - O(n * n!) Time and O(1) Space
C++ provides an in-built function called next_permutation(), that return directly lexicographically in the next greater permutation of the input. The idea is to firstly sort the string s and then call this function until all the permutations are not generated.
Note: Python also have a function permutations() similar to c++.For other programming languages similar function is available in different libraries which can be used to implement same.
Below is given the implementation:
C++
// C++ program to find permutations
// of string using next_permutation
#include <bits/stdc++.h>
using namespace std;
// Function to find all permutation of string
vector<string> findPermutation(string &s){
// sort the string s
sort(s.begin(), s.end());
// stores all unique permutation
vector<string> ans;
// iterate until the next permutation exist
do {
ans.push_back(s);
} while (next_permutation(s.begin(), s.end()));
return ans;
}
int main() {
string s = "ABC";
vector<string> ans = findPermutation(s);
for(auto i: ans){
cout << i << " ";
}
return 0;
}
Python
# Python program to find unique permutations
# of string using itertools.permutations
from itertools import permutations
# Function to find all unique permutations of a string
def findPermutation(s):
# Generate all unique permutations
s = ''.join(sorted(s))
ans = sorted(set(''.join(p) for p in permutations(s)))
return ans
# Main function
if __name__ == "__main__":
s = "ABC"
ans = findPermutation(s)
print(" ".join(ans))
OutputABC ACB BAC BCA CAB CBA
Time Complexity: O(n*n!)
Auxiliary Space: O(1)
Similar Reads
Lexicographic rank of a string using STL You are given a string, find its rank among all its permutations sorted lexicographically. Examples:Input : str[] = "acb"Output : Rank = 2Input : str[] = "string"Output : Rank = 598Input : str[] = "cba"Output : Rank = 6We have already discussed solutions to find Lexicographic rank of string In this
4 min read
Minimum length of string having all permutation of given string. Given a string S where 1\leq length\; of\; S\leq 26 . Assume that all the characters in S are unique. The task is to compute the minimum length of a string which consists of all the permutations of the given string in any order. Note: All permutations must be present as a substring in the resulting
4 min read
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. Examples: Input : str[] = "abc", n = 3 Output : Result = "bac" Explanation : All possible permutation in sorted order: abc, acb, bac, bca, cab, cba Input : str[] = "aba"
6 min read
Find n-th lexicographically permutation of a string | Set 2 Given a string of length m containing lowercase alphabets only. We need to find the n-th permutation of string lexicographic ally. Examples: Input: str[] = "abc", n = 3 Output: Result = "bac" All possible permutation in sorted order: abc, acb, bac, bca, cab, cba Input: str[] = "aba", n = 2 Output: R
11 min read
Number of distinct permutation a String can have We are given a string having only lowercase alphabets. The task is to find out total number of distinct permutation can be generated by that string. Examples: Input : aab Output : 3 Different permutations are "aab", "aba" and "baa". Input : ybghjhbuytb Output : 1663200 A simple solution is to find a
6 min read
Remove duplicates from a string using STL in C++ Given a string S, remove duplicates in this string using STL in C++ Examples: Input: Geeks for geeks Output: Gefgkors Input: aaaaabbbbbb Output: ab Approach: The consecutive duplicates of the string can be removed using the unique() function provided in STL. Below is the implementation of the above
1 min read
Check if Permutation of Pattern is Substring Given two strings txt and pat having lowercase letters, the task is to check if any permutation of pat is a substring of txt. Examples: Input: txt = "geeks", pat = "eke"Output: trueExplanation: "eek" is a permutation of "eke" which exists in "geeks".Input: txt = "programming", pat = "rain"Output: fa
12 min read
Number of even substrings in a string of digits Given a string of digits 0 - 9. The task is to count a number of substrings which when converting into integer form an even number. Examples : Input : str = "1234".Output : 6"2", "4", "12", "34", "234", "1234" are 6 substring which are even.Input : str = "154".Output : 3Input : str = "15".Output : 0
9 min read
XOR of all substrings of a given Binary String Given a binary string str of size N, the task is to calculate the bitwise XOR of all substrings of str. Examples: Input: str = "11"Output: 11Explanation: The substrings of "11" are: 1, 1, and 11.Their XOR = 1 â 1 â 11 = 11 Input: str = "110"Output: 111Explanation: The substrings of 110 are: 1, 1, 0,
6 min read
Print all Substrings of length n possible from the given String Given a string str and an integer N, the task is to print all possible sub-strings of length N. Examples: Input: str = âgeeksforgeeksâ, N = 3Output: gee eek eks ksf sfo for org rge gee eek eksExplanations: All possible sub-strings of length 3 are âgeeâ, âeekâ, âeksâ, âksfâ, âsfoâ, âforâ, âorgâ, ârge
8 min read