![]() |
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"
Approach:
The idea is to use backtracking to generate all possible permutations of given string s. To do so, first initialise an array of string ans[] to list all the permutations and a HashSet res to store all the unique strings in lexicographically sorted order.Start from the 0th index and for each index i, swap the value s[i] with all the elements in its right i.e. from i+1 to n-1, and recur to the index i + 1. If the index i is equal to n, store the resultant string in res, else keep operating similarly for all other indices. Thereafter, swap back the values to original values to initiate backtracking. At last insert the elements in array ans[].
Below is the implementation of the above approach:
ABC ACB BAC BCA CAB CBA
Time Complexity: O(n * n!)
Auxiliary Space: O(n!)
Note: The given problem can also solved using Recursion and STL. These approaches are discussed in below given articles: