Given a string, find all lexicographically next permutations of it.

The words are arranged in the same order in the lexicographic order as they are presumed to appear in a dictionary. For example, the lexicographically next permutation of string ABCD is ABDC, for string ABDC is ACBD, and for string ACBD is ACDB.

Practice this problem

 
A simple solution would be to use std::next_permutation that generates the next greater lexicographic permutation of a string. If the function can determine the next higher permutation, it rearranges the elements and returns true. If that was not possible (because it is already at the largest possible permutation), it rearranges the elements according to the first permutation and returns false.

The implementation can be seen below in C++:

C++


Download  Run Code

Output:

BADC BCAD BCDA BDAC BDCA CABD CADB CBAD CBDA CDAB CDBA DABC DACB DBAC DBCA DCAB DCBA

 
We can also implement our own next_permutation() function. The following algorithm generates the next permutation lexicographically after a given permutation. It changes the permutation in-place.

  • Find the largest index i such that str[i-1] is less than str[i].
  • Return false if i is the first index of the string, meaning that we are already at the highest possible permutation, i.e., the string is sorted in descending order. If i is not the first index of the string, then substring str[i…n) is sorted in descending order, i.e. str[i-1] < str[i] >= str[i+1] >= str[i+2] >= … >= str[n-1].
  • Find the highest index j to the right of index i such that str[j] is greater than str[i-1] and swap the character at index i-1 with index j.
  • Reverse substring str[i…n) and return true.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
BADC BCAD BCDA BDAC BDCA CABD CADB CBAD CBDA CDAB CDBA DABC DACB DBAC DBCA DCAB DCBA

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

 
Note that the above solution can handle strings containing repeated characters and will not print duplicate permutations.

 
Also See:

Find all lexicographically previous permutations of a string