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

In this post, we will discuss about 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 in a similar fashion as they are presumed to appear in a dictionary. For example, the next permutation in lexicographic order for the string 123 is 132.


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 next higher permutation exists else 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 the distinct permutations. Below C++ program demonstrates its usage:


Download   Run Code


231 312 321


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

  • Find 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 else 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 a highest index j to the right of index i such that s[j] is greater than s[i–1] and swap characters at index i-1 with index j.
  • Reverse the substring s[i..n-1] and return true


Download   Run Code


231 312 321


Since there are n! permutations and each permutations takes O(n) time, the time complexity of above solution is O(n.n!) where n is the length of the given string. 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

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)


Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂

Leave a Reply

Notify of