This post discusses std::next_permutation, which can be used to find the lexicographically greater 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 next permutation in lexicographic order for string 123 is 132.

 
The STL provides std::next_permutation, which returns the next permutation in lexicographic order by in-place rearranging the specified object as a lexicographically greater permutation. The function returns true if the next higher 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 first permutation.

std::next_permutation generates the next permutation in just linear time, and it can also handle repeated characters and generates distinct permutations. Its usage can be seen below:

Download  Run Code

Output:

231 312 321

 

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

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

The algorithm can be implemented as follows in C++:

Download  Run Code

Output:

231 312 321

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

 
Also See:

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