A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)

Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB

Here is a solution that is used as a basis in backtracking.

Write a program to print all permutations of a given string

PYTHON Programming

[pastacode lang=”java” manual=”%23%20Python%20program%20to%20print%20all%20permutations%20with%0A%23%20duplicates%20allowed%0A%20%0Adef%20toString(List)%3A%0A%20%20%20%20return%20”.join(List)%0A%20%0A%23%20Function%20to%20print%20permutations%20of%20string%0A%23%20This%20function%20takes%20three%20parameters%3A%0A%23%201.%20String%0A%23%202.%20Starting%20index%20of%20the%20string%0A%23%203.%20Ending%20index%20of%20the%20string.%0Adef%20permute(a%2C%20l%2C%20r)%3A%0A%20%20%20%20if%20l%3D%3Dr%3A%0A%20%20%20%20%20%20%20%20print%20toString(a)%0A%20%20%20%20else%3A%0A%20%20%20%20%20%20%20%20for%20i%20in%20xrange(l%2Cr%2B1)%3A%0A%20%20%20%20%20%20%20%20%20%20%20%20a%5Bl%5D%2C%20a%5Bi%5D%20%3D%20a%5Bi%5D%2C%20a%5Bl%5D%0A%20%20%20%20%20%20%20%20%20%20%20%20permute(a%2C%20l%2B1%2C%20r)%0A%20%20%20%20%20%20%20%20%20%20%20%20a%5Bl%5D%2C%20a%5Bi%5D%20%3D%20a%5Bi%5D%2C%20a%5Bl%5D%20%23%20backtrack%0A%20%0A%23%20Driver%20program%20to%20test%20the%20above%20function%0Astring%20%3D%20%22ABC%22%0An%20%3D%20len(string)%0Aa%20%3D%20list(string)%0Apermute(a%2C%200%2C%20n-1)” message=”Java” highlight=”” provider=”manual”/]

Output:

ABC
ACB
BAC
BCA
CBA
CAB


Algorithm Paradigm:
Backtracking
Time Complexity: O(n*n!) Note that there are n! permutations and it requires O(n) time to print a a permutation.

[ad type=”banner”]