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.
Input: str = “gfg”, K = 10
There are 10 possible subsequence of the given string “gggggffg”. They are:
Input: str = “code”, K = 20
There are 20 possible subsequence of the string “cccccoodde”.
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 size of the given string to stores 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 characters ch to the resultant string s.
Below is the implementation of the above approach:
Time Complexity: O(N*log2(log2(N)))
Auxiliary Space: O(K)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Count subsequences in first string which are anagrams of the second string
- Print all subsequences of a string
- Count of 'GFG' Subsequences in the given string
- Print all subsequences of a string using ArrayList
- Print all subsequences of a string in Python
- Number of subsequences in a string divisible by n
- Lexicographically smallest permutation of a string with given subsequences
- Number of subsequences in a given binary string divisible by 2
- Print all subsequences of a string | Iterative Method
- Number of subsequences as "ab" in a string repeated K times
- Minimum cost to construct a string
- Construct a binary string following the given constraints
- Print all Subsequences of String which Start with Vowel and End with Consonant.
- Generating distinct subsequences of a given string in lexicographic order
- Minimum number of subsequences required to convert one string to another
- Number of ways to partition a string into two balanced subsequences
- Construct the Cypher string based on the given conditions
- Count the number of ways to construct the target string
- Construct Binary Tree from String with bracket representation
- Minimum number of subsequences required to convert one string to another using Greedy Algorithm
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : sapnasingh4991