Open In App

Permutations of given String

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
526 Likes
Like
Report

Given a string s, the task is to return all permutations of a given string in lexicographically sorted order.

Note: A permutation is the rearrangement of all the elements of a string. Duplicate arrangement can exist.

Examples:

Input: s = "ABC"
Output: "ABC", "ACB", "BAC", "BCA", "CAB", "CBA"

Input: s = "XY"
Output: "XY", "YX"

Input: s = "AAA"
Output: "AAA", "AAA", "AAA", "AAA", "AAA", "AAA"

The idea is to use backtracking to generate all possible permutations of given string s. To do so, first initialize an array of string ans[] to store all the permutations. Start from the 0th index and for each index i, swap the value s[i] with all the elements in its right i.e. from i+1 to n-1, and recur to the index i + 1. If the index i is equal to n, store the resultant string in ans[], else keep operating similarly for all other indices. Thereafter, swap back the values to original values to initiate backtracking. At last sort the array ans[].

illustration:

4

Below is the implementation of the above approach:

C++
Java Python C# JavaScript

Output
ABC ACB BAC BCA CAB CBA 

Time Complexity: O(n * n!)
Auxiliary Space: O(n!)

Related articles:


Write a program to print all permutations of a given string

Similar Reads