This post will discuss how to find permutations of a string using iteration.

In the previous post, we have seen the recursive implementation to find permutations of a string using backtracking. This post will cover iterative implementation for the same.

Practice this problem

The recursive implementation doesn’t handle strings containing duplicate characters and prints the duplicate permutations. For example, for the string ABA, the permutations BAA, ABA, and AAB gets printed twice. The following iterative implementation using std::next_permutation can handle strings with duplicate characters and don’t repeat the permutations.

1. Using std::next_permutation

The idea is to sort the string and repeatedly call std::next_permutation to generate the next greater lexicographic permutation of a string.

The iterative implementation below avoids using std::next_permutation and implements the following in-place algorithm to generate the next permutation lexicographically:

  1. Find the largest index i such that str[i-1] is less than str[i].
  2. Terminate the algorithm if i happens to be the first index of the string, since we are already at the highest possible permutation.
  3. If i is not the first index of the string, then the substring str[i…n-1] is sorted in reverse order, i.e., str[i-1] < str[i] >= str[i+1] >= str[i+2] >= … >= str[n-1].
  4. 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.
  5. Reverse substring str[i…n-1] and repeat.

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

C++


Download  Run Code

Output:

ABC ACB BAC BCA CAB CBA

Java


Download  Run Code

Output:

ABC ACB BAC BCA CAB CBA

Python


Download  Run Code

Output:

ABC ACB BAC BCA CAB CBA

We can also sort the string in reverse order and repeatedly calls std::prev_permutation to generate the previous lexicographic permutation of a string.

2. Using Controller Array

Please refer to this link for details on the below algorithm.

C++


Download  Run Code

Output:

ABC BAC CAB ACB BCA CBA

Java


Download  Run Code

Output:

ABC BAC CAB ACB BCA CBA

Python


Download  Run Code

Output:

ABC BAC CAB ACB BCA CBA

3. Using List

The following implementation uses the list to store the partially constructed permutations and then use those partial permutations to build the final permutations in later iterations:

C++


Download  Run Code

Output:

CBA BCA BAC CAB ACB ABC

Java


Download  Run Code

Output:

[CAB, ACB, ABC, CBA, BCA, BAC]

The time complexity of the above solutions remains the same as recursive implementation, i.e., O(n!), where n is the length of the input string.

 
References:

1. Stack Overflow

2. Permutation Algorithms Using Iteration and the Base-N-Odometer Model (Without Recursion)