Skip to content
Related Articles

Related Articles

Improve Article

Print all lexicographical greater permutations of a given string

  • Difficulty Level : Expert
  • Last Updated : 22 Jun, 2020

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:




// C++ program to print the lexicographically
// greater strings then the given string
#include <bits/stdc++.h>
using namespace std;
  
// Function to print the lexicographically
// greater strings then the given string
void print_lexiStrings(string S)
{
  
    // Condition to check if there is no
    // string which is lexicographically
    // greater than string S
    if (!next_permutation(S.begin(), S.end()))
        cout << "-1";
  
    // Move to the previous permutation
    prev_permutation(S.begin(), S.end());
  
    // Iterate over all the
    // lexicographically greater strings
    while (next_permutation(S.begin(), S.end())) {
        cout << S << "\n";
    }
}
  
// Driver Code
int main()
{
  
    string S = "ABC";
  
    print_lexiStrings(S);
}
Output:
ACB
BAC
BCA
CAB
CBA

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :