0

The algorithm which I know is the below but why I hate this approach is it's time complexity is O((n+1)!) too worse in case of large strings

Start by sorting the string and printing that as the first permutation.
Now, we can find the next permutation as follows:

Let i be the last index such that input[i] < input[i + 1]. If there is no such index, then we’re done. Let j be the last index such that input[i] < input[j]. Swap input[i] with input[j]. Reverse input[i + 1] through input[input.length - 1].

Is there any better approach than the above one ?(If explanation is through code then please consider c or c++)... just I am expecting a better algorithm with lesser time complexity than the above one

nikhil ponnuru
  • 288
  • 1
  • 6
  • 13

3 Answers3

6

There are n! permutations for a string with length n. Simply printing them is O(n * n!), how can you expect it will be much more efficient?

Xiaotian Pei
  • 3,210
  • 21
  • 40
3

Even the standard C++ implementation to print permutations of a string follows exactly same algorithm (std::next_permutation and std::prev_permutation)

std::string s;
std::sort(s.begin(), s.end());
do {
    std::cout << s << std::endl;
} while(std::next_permutation(s.begin(), s.end()));
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50
0

Keep in mind that in C++ the STL has std::next_permutation that does the job you need

marom
  • 5,064
  • 10
  • 14