![]() |
VOOZH | about |
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.
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.
ABC ACB BAC BCA CAB CBA
Time Complexity: O(n*n!)
Auxiliary Space: O(n)
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:
ABC ACB BAC BCA CAB CBA
Time Complexity: O(n*n!)
Auxiliary Space: O(1)