CSES Solutions - Creating Strings Last Updated : 15 Mar, 2024 Comments Improve Suggest changes Like Article Like Report Given a string S, your task is to generate all different strings that can be created using its characters. Examples: Input: S = "aabac"Output: 20aaabcaaacbaabacaabcaaacabaacbaabaacabacaabcaaacaabacabaacbaabaaacbaacabacaabcaaacaaabcaabacabaacbaaa Explanation: 20 unique strings can be generated by rearranging letters of the string "aabac". Input: S = "aba"Output: 3aabababaaExplanation: 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: C++ #include <bits/stdc++.h> using namespace std; // function to generate all permutations of string S set<string> solve(string S) { int N = S.length(); sort(S.begin(), S.end()); // set to store all the unique permutations set<string> uniqueStrings; do { uniqueStrings.insert(S); } while (next_permutation(S.begin(), S.end())); return uniqueStrings; } int main() { // Sample Input string S = "aba"; set<string> uniqueStrings = solve(S); cout << uniqueStrings.size() << "\n"; for (string str : uniqueStrings) { cout << str << "\n"; } } Java import java.util.*; public class Permutations { // Function to generate all permutations of string S static Set<String> solve(String S) { int N = S.length(); char[] charArray = S.toCharArray(); Arrays.sort(charArray); // Set to store all the unique permutations Set<String> uniqueStrings = new HashSet<>(); do { uniqueStrings.add(new String(charArray)); } while (nextPermutation(charArray)); return uniqueStrings; } // Function to find the next lexicographically greater permutation static boolean nextPermutation(char[] array) { int i = array.length - 2; while (i >= 0 && array[i] >= array[i + 1]) { i--; } if (i < 0) { return false; // No next permutation is possible } int j = array.length - 1; while (array[j] <= array[i]) { j--; } // Swap the characters at positions i and j char temp = array[i]; array[i] = array[j]; array[j] = temp; // Reverse the suffix after i reverse(array, i + 1, array.length - 1); return true; } // Function to reverse the characters in the array from start to end static void reverse(char[] array, int start, int end) { while (start < end) { char temp = array[start]; array[start] = array[end]; array[end] = temp; start++; end--; } } public static void main(String[] args) { // Sample Input String S = "aba"; Set<String> uniqueStrings = solve(S); System.out.println(uniqueStrings.size()); for (String str : uniqueStrings) { System.out.println(str); } } } C# using System; using System.Collections.Generic; using System.Linq; public class PermutationGenerator { // Function to generate all permutations of string S public static HashSet<string> Solve(string S) { int N = S.Length; char[] charArray = S.ToCharArray(); Array.Sort(charArray); S = new string(charArray); // set to store all the unique permutations HashSet<string> uniqueStrings = new HashSet<string>(); do { uniqueStrings.Add(S); } while (NextPermutation(ref S)); return uniqueStrings; } // Function to generate the next lexicographically greater permutation private static bool NextPermutation(ref string S) { char[] charArray = S.ToCharArray(); int i = charArray.Length - 2; while (i >= 0 && charArray[i] >= charArray[i + 1]) { i--; } if (i < 0) { return false; } int j = charArray.Length - 1; while (charArray[j] <= charArray[i]) { j--; } char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; Array.Reverse(charArray, i + 1, charArray.Length - i - 1); S = new string(charArray); return true; } // Main method public static void Main(string[] args) { // Sample Input string S = "aba"; HashSet<string> uniqueStrings = Solve(S); Console.WriteLine(uniqueStrings.Count); foreach (string str in uniqueStrings) { Console.WriteLine(str); } } } JavaScript // function to generate all permutations of string S function solve(S) { const N = S.length; const sortedS = S.split('').sort().join(''); // Set to store all the unique permutations const uniqueStrings = new Set(); const generatePermutations = (str, chosen) => { if (str.length === 0) { uniqueStrings.add(chosen); return; } for (let i = 0; i < str.length; i++) { const remaining = str.slice(0, i) + str.slice(i + 1); generatePermutations(remaining, chosen + str[i]); } }; generatePermutations(sortedS, ''); return uniqueStrings; } // Sample Input const S = "aba"; const uniqueStrings = solve(S); console.log(uniqueStrings.size); uniqueStrings.forEach(str => { console.log(str); }); Python3 from itertools import permutations # Function to generate all permutations of string S def solve(S): # Sort the string to ensure unique permutations S_sorted = sorted(S) # Use set to store all the unique permutations unique_strings = set() # Generate permutations and add them to the set for perm in permutations(S_sorted): unique_strings.add(''.join(perm)) return unique_strings def main(): # Sample Input S = "aba" # Call the function to find unique permutations unique_strings = solve(S) # Print the number of unique permutations print(len(unique_strings)) # Print each unique permutation for string in unique_strings: print(string) if __name__ == "__main__": main() Output3 aab aba baaTime Complexity: O(N * N!), where N is the length of input string S.Auxiliary Space: O(N) Comment More infoAdvertise with us A alphacozeop Follow Improve Article Tags : Competitive Programming permutation CSES Problems Practice Tags : permutation Similar Reads Complete CP GuideCompetitive Programming - A Complete GuideCompetitive Programming is a mental sport that enables you to code a given problem under provided constraints. The purpose of this article is to guide every individual possessing a desire to excel in this sport. This article provides a detailed syllabus for Competitive Programming designed by indust5 min readBasicsDSA TutorialData structures manage how data is stored and accessed, while Algorithms focus on processing this data. Examples of data structures are Array, Linked List, Tree and Heap, and examples of algorithms are Binary Search, Quick Sort and Merge Sort. Why to Learn DSA?Foundation for almost every software li7 min readMaths for DSAMaths is a fundamental component of learning Data Structure and Algorithms, just like in programming. Maths is primarily used to evaluate the effectiveness of different algorithms. However, there are situations when the answer requires some mathematical understanding or the problem has mathematical15+ min readMathematical AlgorithmsThe following is the list of mathematical coding problem ordered topic wise. Please refer Mathematical Algorithms (Difficulty Wise) for the difficulty wise list of problems. GCD and LCM: GCD of Two Numbers LCM of Two Numbers LCM of array GCD of array Basic and Extended Euclidean Steinâs Algorithm fo5 min readBit manipulationBit Manipulation for Competitive ProgrammingBit manipulation is a technique in competitive programming that involves the manipulation of individual bits in binary representations of numbers. It is a valuable technique in competitive programming because it allows you to solve problems efficiently, often reducing time complexity and memory usag15+ min readBit Tricks for Competitive ProgrammingIn competitive programming or in general, some problems seem difficult but can be solved very easily with little concepts of bit magic. We have discussed some tricks below in the previous post.Bitwise Hacks for Competitive Programming One-Liner Hacks of Bit Manipulation:One-Liner CodeFunctionx&17 min readBitwise Hacks for Competitive ProgrammingPrerequisite: It is recommended to refer Interesting facts about Bitwise Operators How to set a bit in the number 'num': If we want to set a bit at nth position in the number 'num', it can be done using the 'OR' operator( | ).  First, we left shift '1' to n position via (1<<n)Then, use the 'O14 min readDP for CPDynamic Programming (DP) IntroductionDynamic Programming is a commonly used algorithmic technique used to optimize recursive solutions when same subproblems are called again.The core idea behind DP is to store solutions to subproblems so that each is solved only once. To solve DP problems, we first write a recursive solution in a way t15+ min readDynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of3 min readDP on Trees for Competitive ProgrammingDynamic Programming (DP) on trees is a powerful algorithmic technique commonly used in competitive programming. It involves solving various tree-related problems by efficiently calculating and storing intermediate results to optimize time complexity. By using the tree structure, DP on trees allows p15+ min readDynamic Programming in Game Theory for Competitive ProgrammingIn the fast-paced world of competitive programming, mastering dynamic programming in game theory is the key to solving complex strategic challenges. This article explores how dynamic programming in game theory can enhance your problem-solving skills and strategic insights, giving you a competitive e15+ min readAdvancedGraph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net3 min readSegment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree3 min readBinary Indexed Tree or Fenwick TreeBinary Indexed Trees are used for problems where we have following types of multiple operations on a fixed sized.Prefix Operation (Sum, Product, XOR, OR, etc). Note that range operations can also be solved using prefix. For example, range sum from index L to R is prefix sum till R (included minus pr15 min readArray Range QueriesThe array range query problem can be defined as follows: Given an array of numbers, the array range query problem is to build a data structure that can efficiently answer queries of a particular type mentioned in terms of an interval of the indices. The specific query can be of type - maximum elemen3 min read Like