This post discusses std::prev_permutation, which can be used to find the lexicographically smaller permutations of a string.

The lexicographic or lexicographical order (aka lexical order, dictionary order, alphabetical order) means that the words are arranged as they are presumed to appear in a dictionary. For example, the previous permutation in lexicographic order for string 213 is 132.

 
The STL provides std::prev_permutation, which returns the previous permutation in lexicographic order by in-place rearranging the specified object as a lexicographically smaller permutation. The function returns true if the previous permutation exists; otherwise, it returns false to indicate that the object is already at the highest possible permutation and reset the range according to the last permutation.

std::prev_permutation generates the previous permutation in mere linear time and handles repeated characters to generate the distinct permutations. Following is the C++ program which demonstrates its usage:

Download  Run Code

Output:

231 213 132 123

 

We can also implement our prev_permutation method. The following in-place algorithm lexicographically generates the previous permutation after a given permutation:

  • Find the largest index i such that s[i-1] > s[i].
  • If i is the first index of the string, the permutation is the first permutation; otherwise, s[i…n-1] is sorted in natural order, i.e., s[i-1] > s[i] <= s[i+1] <= s[i+2] <= … <= s[n-1].
  • Find the highest index j such that j >= i and s[j] < s[i-1] and swap the character at index i-1 with index j.
  • Reverse substring s[i…n-1] and return true.

The implementation can be seen below in C++:

Download  Run Code

Output:

231 213 132 123

 
Since there are n! permutations for a string of length n, and each permutation takes linear time, the time complexity of the above solution is O(n.n!). The worst case happens when the string contains all distinct elements, and the best-case happens when the string contains all repeated characters.

 
Also See:

std::next_permutation | Overview and Implementation in C++