Print all lexicographical greater permutations of a given string
Given a string S, print those permutations of string S which are lexicographically greater than S. If there is no such permutation of string, print -1. Examples:
Input : BCA Output : CAB, CBA Explanation: Here, S = “BCA”, and there are 2 strings “CAB, CBA” which are lexicographically greater than S. Input : CBA Output : -1 There is no string which is lexicographically greater than S, so the output is -1.
Approach: To solve the problem mentioned above we will use STL. Use next_permuation() and prev_permutation() functions to check and the lexicographically greater strings. If the string is greater then print it otherwise print -1. Below is the implementation of above approach:
ACB BAC BCA CAB CBA
Time Complexity : O(N*N!), As next_permutation takes O(N!) for finding all the permutations and in order to print the string it will take O(N) time complexity, where N is the length of the string.
Auxiliary Space : O(1)