Given a word, find the lexicographically greater permutation of it. For example, lexicographically next permutation of “gfg” is “ggf” and 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’.

Let us look at the code snippet here :

`// Find the next lexicographically ` `// greater permutation of a word ` ` ` `#include <algorithm> ` `#include <iostream> ` ` ` `using` `namespace` `std; ` ` ` `int` `main() ` `{ ` ` ` `string s = { ` `"gfg"` `}; ` ` ` `bool` `val ` ` ` `= next_permutation(s.begin(), ` ` ` `s.end()); ` ` ` `if` `(val == ` `false` `) ` ` ` `cout << ` `"No Word Possible"` ` ` `<< endl; ` ` ` `else` ` ` `cout << s << endl; ` ` ` `return` `0; ` `} ` |

*chevron_right*

*filter_none*

**Output:**

ggf

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:

1) An sequence sorted in descending order does not have next permutation. For example edcba” does not have next permutation.

2) For a sequence which is not sorted in descending order for example “abedc”, we can follow below steps.

……….a) Traverse from right and find the first item that is not following the descending order. For example in “abedc”, the character ‘b’ does not follow the descending order.

……….b) Swap the found character with closest greater (or smallest greater) element on right side of it. In case of “abedc”, we have ‘c’ as the closest greater element. After swapping ‘b’ and ‘c’, string becomes “acedb”.

……….c) After swapping, sort the string after the position of character found in step **a**. After sorting the substring “edb” of “acedb”, we get “**acbde**” which is the required next permutation.

Optimizations in step 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.

`// Find the next lexicographically ` `// greater permutation of a word ` ` ` `#include <iostream> ` ` ` `using` `namespace` `std; ` ` ` `void` `swap(` `char` `* a, ` `char` `* b) ` `{ ` ` ` `if` `(*a == *b) ` ` ` `return` `; ` ` ` `*a ^= *b; ` ` ` `*b ^= *a; ` ` ` `*a ^= *b; ` `} ` `void` `rev(string& s, ` `int` `l, ` `int` `r) ` `{ ` ` ` `while` `(l < r) ` ` ` `swap(&s[l++], &s[r--]); ` `} ` ` ` `int` `bsearch` `(string& s, ` `int` `l, ` `int` `r, ` `int` `key) ` `{ ` ` ` `int` `index = -1; ` ` ` `while` `(l <= r) { ` ` ` `int` `mid = l + (r - l) / 2; ` ` ` `if` `(s[mid] <= key) ` ` ` `r = mid - 1; ` ` ` `else` `{ ` ` ` `l = mid + 1; ` ` ` `if` `(index == -1 || s[index] >= s[mid]) ` ` ` `index = mid; ` ` ` `} ` ` ` `} ` ` ` `return` `index; ` `} ` ` ` `bool` `nextpermutation(string& s) ` `{ ` ` ` `int` `len = s.length(), i = len - 2; ` ` ` `while` `(i >= 0 && s[i] >= s[i + 1]) ` ` ` `--i; ` ` ` `if` `(i < 0) ` ` ` `return` `false` `; ` ` ` `else` `{ ` ` ` `int` `index = ` `bsearch` `(s, i + 1, len - 1, s[i]); ` ` ` `swap(&s[i], &s[index]); ` ` ` `rev(s, i + 1, len - 1); ` ` ` `return` `true` `; ` ` ` `} ` `} ` ` ` `// Driver code ` `int` `main() ` `{ ` ` ` `string s = { ` `"gfg"` `}; ` ` ` `bool` `val = nextpermutation(s); ` ` ` `if` `(val == ` `false` `) ` ` ` `cout << ` `"No Word Possible"` `<< endl; ` ` ` `else` ` ` `cout << s << endl; ` ` ` `return` `0; ` `} ` `// This code is contributed by Mysterious Mind ` |

*chevron_right*

*filter_none*

**Output:**

ggf

**Time Complexity:**

- In the worst case, the first step of next_permutation takes O(n) time.
- Binary search takes O(logn) time.
- Reverse takes O(n) time.

**Overall time complexity is O(n).**

Where n is the length of the string.

**Reference:** http://www.cplusplus.com/reference/algorithm/next_permutation/

This article is contributed by **Harshit Gupta**. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

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.

## Recommended Posts:

- Find a string such that every character is lexicographically greater than its immediate next character
- Lexicographically next string
- Lexicographically next greater string using same character set
- Replace every vowels with lexicographically next vowel in a String
- Lexicographically n-th permutation of a string
- Lexicographically smallest permutation of {1, .. n} such that no. and position do not match
- Lexicographically smallest permutation with distinct elements using minimum replacements
- Lexicographically smallest permutation with no digits at Original Index
- Lexicographically Smallest Permutation of length N such that for exactly K indices, a[i] > a[i] + 1
- Lexicographically smallest permutation of size A having B integers exceeding all preceeding integers
- How to find Lexicographically previous permutation?
- Lexicographically smallest array after at-most K consecutive swaps
- Lexicographically first palindromic string
- Lexicographically minimum string rotation | Set 1
- Lexicographically smallest rotated sequence | Set 2
- Lexicographically first alternate vowel and consonant string
- Compare two strings lexicographically in Java
- Lexicographically largest subsequence such that every character occurs at least k times
- Lexicographically smallest string whose hamming distance from given string is exactly K
- Construct lexicographically smallest palindrome