Lexicographically Next Permutation in C++
All the permutations of a word when arranged in a dictionary, the order of words so obtained is called lexicographical order. in Simple words, it is the one that has all its elements sorted in ascending order, and the largest has all its elements sorted in descending order.
lexicographically is nothing but the greater permutation of it.
For reference: a b c d e f g h i j k l m n o p q r s t u v w x y z
For example, lexicographically next permutation of “gfg” is “ggf” and the next permutation of “acb” is “bac”.
Note: In some cases, the next lexicographically greater word might not exist, e.g, “aaa” and “edcba”.
In C++, there is a specific function that saves us from a lot of code. It’s in the file #include <algorithm>. The function is next_permutation(a.begin(), a.end()).
It returns ‘true’ if the function could rearrange the object as a lexicographically greater permutation. Otherwise, the function returns ‘false’.
The same program can also be implemented without using STL. Below is the code snippet for the same.
The Idea is Based on the Following Facts:
- A sequence sorted in descending order does not have the next permutation. For example “edcba” does not have the next permutation.
- For a sequence that is not sorted in descending order for example “abedc”, we can follow these steps.
- a) Traverse from the right and find the first item that is not following the ascending order. For example in “abedc”, the character ‘b’ does not follow the ascending order.
- b) Swap the found character with the closest greater (or smallest greater) element on the right side of it. In the case of “abedc”, we have ‘c’ as the closest greater element. After swapping ‘b’ and ‘c’, the string becomes “acedb”.
- c) After swapping, reverse the string after the position of the character found in step a. After reversing the substring “edb” of “acedb”, we get “acbde” which is the required next permutation.
Optimizations in steps b) and c)
a) Since the sequence is sorted in decreasing order, we can use binary search to find the closest greater element.
c) Since the sequence is already sorted in decreasing order (even after swapping as we swapped with the closest greater), we can get the sequence sorted (in increasing order) after reversing it.
- In the worst case, the first step of next_permutation takes O(n) time.
- The binary search takes O(log n) time.
- The reverse takes O(n) time.
Overall time complexity is O(n). Where n is the length of the string.
Auxiliary Space is O(1), because no extra space is used.
This article is contributed by Harshit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article on write.geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.