VOOZH about

URL: https://www.geeksforgeeks.org/dsa/cses-solutions-creating-strings/

⇱ CSES Solutions - Creating Strings - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

CSES Solutions - Creating Strings

Last Updated : 15 Mar, 2024

Given a string S, your task is to generate all different strings that can be created using its characters.

Examples:

Input: S = "aabac"
Output:
20
aaabc
aaacb
aabac
aabca
aacab
aacba
abaac
abaca
abcaa
acaab
acaba
acbaa
baaac
baaca
bacaa
bcaaa
caaab
caaba
cabaa
cbaaa

Explanation: 20 unique strings can be generated by rearranging letters of the string "aabac".

Input: S = "aba"
Output:
3
aab
aba
baa
Explanation: 3 unique strings can be generated by rearranging letters of the string "aba".

Approach: To solve the problem, follow the below idea:

The problem can be solved by generating all the possible permutations of the input strings. Since some of these permutations can be same, so we can insert all the permutations to a set. After inserting all the permutations, we can print all the unique strings.

Step-by-step algorithm:

  • Generate all the permutations of the input string.
  • Insert all the strings to a set to avoid printing duplicate strings.
  • Iterate over the set and print all the unique strings.

Below is the implementation of the algorithm:


Output
3
aab
aba
baa

Time Complexity: O(N * N!), where N is the length of input string S.
Auxiliary Space: O(N)

Comment
Article Tags: