Construct a string that has exactly K subsequences from given string Last Updated : 18 May, 2021 Summarize Comments Improve Suggest changes Share Like Article Like Report Given a string str and an integer K, the task is to find a string S such that it has exactly K subsequences of given string str. Examples: Input: str = "gfg", K = 10 Output: gggggffg Explanation: There are 10 possible subsequence of the given string "gggggffg". They are: 1. gggggffg 2. gggggffg 3. gggggffg 4. gggggffg 5. gggggffg 6. gggggffg 7. gggggffg 8. gggggffg 9. gggggffg 10. gggggffg.Input: str = "code", K = 20 Output: cccccoodde Explanation: There are 20 possible subsequence of the string "cccccoodde". Approach:To solve the problem mentioned above we have to follow the steps given below: The idea is to find the prime factors of K and store the prime factors(say factors).Create an empty array count of the size of the given string to store the count of each character in the resultant string s. Initialize the array with 1.Now pop elements from the list factors and multiply to each position of array in a cyclic way until the list becomes empty. Finally, we have the count of each character of str in the array.Iterate in the array count[] and append the number of characters for each character ch to the resultant string s. Below is the implementation of the above approach: C++ // C++ program for the above approach #include <bits/stdc++.h> #include <iostream> using namespace std; // Function that computes the string s void printSubsequenceString(string str, long long k) { // Length of the given string str int n = str.size(); int i; // List that stores all the prime // factors of given k vector<long long> factors; // Find the prime factors for (long long i = 2; i <= sqrt(k); i++) { while (k % i == 0) { factors.push_back(i); k /= i; } } if (k > 1) factors.push_back(k); // Initialize the count of each // character position as 1 vector<long long> count(n, 1); int index = 0; // Loop until the list // becomes empty while (factors.size() > 0) { // Increase the character // count by multiplying it // with the prime factor count[index++] *= factors.back(); factors.pop_back(); // If we reach end then again // start from beginning if (index == n) index = 0; } // Store the output string s; for (i = 0; i < n; i++) { while (count[i]-- > 0) { s += str[i]; } } // Print the string cout << s; } // Driver code int main() { // Given String string str = "code"; long long k = 20; // Function Call printSubsequenceString(str, k); return 0; } Java // Java program for the above approach import java.util.*; class GFG{ // Function that computes the String s static void printSubsequenceString(String str, int k) { // Length of the given String str int n = str.length(); int i; // List that stores all the prime // factors of given k Vector<Integer> factors = new Vector<Integer>(); // Find the prime factors for (i = 2; i <= Math.sqrt(k); i++) { while (k % i == 0) { factors.add(i); k /= i; } } if (k > 1) factors.add(k); // Initialize the count of each // character position as 1 int []count = new int[n]; Arrays.fill(count, 1); int index = 0; // Loop until the list // becomes empty while (factors.size() > 0) { // Increase the character // count by multiplying it // with the prime factor count[index++] *= factors.get(factors.size() - 1); factors.remove(factors.get(factors.size() - 1)); // If we reach end then again // start from beginning if (index == n) index = 0; } // Store the output String s = ""; for (i = 0; i < n; i++) { while (count[i]-- > 0) { s += str.charAt(i); } } // Print the String System.out.print(s); } // Driver code public static void main(String[] args) { // Given String String str = "code"; int k = 20; // Function Call printSubsequenceString(str, k); } } // This code is contributed by sapnasingh4991 Python3 # Python3 program for # the above approach import math # Function that computes # the string s def printSubsequenceString(st, k): # Length of the given # string str n = len(st) # List that stores # all the prime # factors of given k factors = [] # Find the prime factors sqt = (int(math.sqrt(k))) for i in range (2, sqt + 1): while (k % i == 0): factors.append(i) k //= i if (k > 1): factors.append(k) # Initialize the count of each # character position as 1 count = [1] * n index = 0 # Loop until the list # becomes empty while (len(factors) > 0): # Increase the character # count by multiplying it # with the prime factor count[index] *= factors[-1] factors.pop() index += 1 # If we reach end then again # start from beginning if (index == n): index = 0 # store output s = "" for i in range (n): while (count[i] > 0): s += st[i] count[i] -= 1 # Print the string print (s) # Driver code if __name__ == "__main__": # Given String st = "code" k = 20 # Function Call printSubsequenceString(st, k) # This code is contributed by Chitranayal C# // C# program for the above approach using System; using System.Collections.Generic; class GFG{ // Function that computes the String s static void printSubsequenceString(String str, int k) { // Length of the given String str int n = str.Length; int i; // List that stores all the prime // factors of given k List<int> factors = new List<int>(); // Find the prime factors for (i = 2; i <= Math.Sqrt(k); i++) { while (k % i == 0) { factors.Add(i); k /= i; } } if (k > 1) factors.Add(k); // Initialize the count of each // character position as 1 int []count = new int[n]; for (i = 0; i < n; i++) count[i] = 1; int index = 0; // Loop until the list // becomes empty while (factors.Count > 0) { // Increase the character // count by multiplying it // with the prime factor count[index++] *= factors[factors.Count - 1]; factors.Remove(factors[factors.Count - 1]); // If we reach end then again // start from beginning if (index == n) index = 0; } // Store the output String s = ""; for (i = 0; i < n; i++) { while (count[i]-- > 0) { s += str[i]; } } // Print the String Console.Write(s); } // Driver code public static void Main(String[] args) { // Given String String str = "code"; int k = 20; // Function Call printSubsequenceString(str, k); } } // This code is contributed by sapnasingh4991 JavaScript <script> // Javascript program for the above approach // Function that computes the string s function printSubsequenceString(str, k) { // Length of the given string str let n = str.length; let i; // List that stores all the prime // factors of given k let factors = new Array(); // Find the prime factors for (let i = 2; i <= Math.sqrt(k); i++) { while (k % i == 0) { factors.push(i); k /= i; } } if (k > 1) factors.push(k); // Initialize the count of each // character position as 1 let count = new Array(n).fill(1); let index = 0; // Loop until the list // becomes empty while (factors.length > 0) { // Increase the character // count by multiplying it // with the prime factor count[index++] *= factors[factors.length - 1]; factors.pop(); // If we reach end then again // start from beginning if (index == n) index = 0; } // Store the output let s = new String(); for (i = 0; i < n; i++) { while (count[i]-- > 0) { s += str[i]; } } // Print the string document.write(s); } // Driver code // Given String let str = "code"; let k = 20; // Function Call printSubsequenceString(str, k); // This code is contributed by _saurabh_jaiswal </script> Output: cccccoodde Time Complexity: O(N*log2(log2(N))) Auxiliary Space: O(K) Comment More infoAdvertise with us Next Article Construct a string that has exactly K subsequences from given string G Ganeshchowdharysadanala Follow Improve Article Tags : Strings Greedy Pattern Searching Searching Mathematical Hash DSA subsequence sieve prime-factor Prime Number +7 More Practice Tags : GreedyHashMathematicalPattern SearchingPrime NumberSearchingsieveStrings +4 More Similar Reads DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on 7 min read Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s 12 min read Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge 14 min read Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st 2 min read Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta 15+ min read Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc 15 min read Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T 9 min read Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous 4 min read Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ 3 min read Like