Permutation of a Given String using Inbuilt Function (original) (raw)

Last Updated : 31 Oct, 2025

The task is to generate all the possible permutations of a given string. A permutation of a string is a rearrangement of its characters. For example, the permutations of "ABC" are "ABC", "ACB", "BAC", "BCA", "CAB", and "CBA". The number of permutations of a string with n unique characters is n! (factorial of n).

itertools module in Python provides a simple function called permutations that can generate all possible permutations of a string. This method is the easiest and most efficient, especially when working with built-in Python libraries.

Python `

import itertools

s = "GFG" li = [''.join(p) for p in itertools.permutations(s)] print(li)

`

**Explanation:

Using Recursion

Recursion repeatedly breaks the problem into smaller parts. In string permutation, it means choosing one character and recursively arranging the remaining characters, generating all possible orderings systematically.

Python `

def permute(s, s2): if len(s) == 0: print(s2, end=' ') return

for i in range(len(s)):
    char = s[i]
    left_s = s[0:i]
    right_s = s[i+1:]
    rest = left_s + right_s
    permute(rest, s2 + char)

s1 = "GFG" s2 = "" permute(s1, s2)

`