Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Minimize length of a string by removing occurrences of another string from it as a substring
Next article icon

Minimize steps to form string S from any random string of length K using a fixed length subsequences

Last Updated : 11 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string S consisting of N characters and a positive integer K, the task is to find the minimum number of operations required to generate the string S from a random string temp of size K and inserting the subsequence of any fixed length from the random string in the random string. If it is impossible to generate the string S, then print "-1".

Examples:

Input: S = "toffee", K = 4
Output: 2 tofe
Explanation:
Consider the random string temp as "tofe" which is of length K(= 4) and perform the following steps:
Operation 1: Take a subsequence of length 1 from string temp as 'f' and after inserting the subsequence in the string "tofe" modifies the string to "toffe".
Operation 2: Take a subsequence of length 1 from string temp as 'e' and after inserting the subsequence in the string "toffe" modifies the string to "toffee".
Therefore, the minimum number of operations required is 2.

Input: S = "book", K = 2
Output: -1

Approach: This problem can be solved by using Greedy Approach and Binary Search. Follow the steps below to solve this problem:

  • Initialize an array, say amounts[] that stores the frequency of each character of string S.
  • Iterate in the range [0, N - 1] using the variable i and increment the frequency of the current character by 1 in the array amounts[].
  • Find count unique characters in the string S and store it in a variable, say, count.
  • If the count is greater than N, then return -1.
  • Now, perform the Binary Search to find the resultant string and perform the following steps:
  • Initialize two variables high as 105 and low as 0.
  • Iterate until the value of (high - low) is greater than 1 and perform the following steps:
    • Update the value of total as 0 and mid as (high + low) / 2.
    • Iterate in the range [0, 25] using the variable i and if the value of amounts[i] is greater than 0, then increment the total by (amounts[i] - 1)/mid + 1.
    • If the total is less than equal to N, then update the value of high as mid. Otherwise, update the value of low as mid.
  • After completing the above steps, print the value of high and iterate in the range[0, 25], and print the resultant string.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Function to find the minimum number // of string required to generate // the original string void findString(string S, int K) {     // Stores the frequency of each     // character of String S     int amounts[26];      // Iterate over the range [0, 25]     for (int i = 0; i < 26; i++) {         amounts[i] = 0;     }      // Stores the frequency of each     // character of String S     for (int i = 0; i < S.length(); i++) {         amounts[int(S[i]) - 97]++;     }      int count = 0;      // Count unique characters in S     for (int i = 0; i < 26; i++) {         if (amounts[i] > 0)             count++;     }      // If unique characters is greater     // then N, then return -1     if (count > K) {         cout << "-1";     }      // Otherwise     else {          string ans = "";         int high = 100001;         int low = 0;         int mid, total;          // Perform Binary Search         while ((high - low) > 1) {              total = 0;              // Find the value of mid             mid = (high + low) / 2;              // Iterate over the range             // [0, 26]             for (int i = 0; i < 26; i++) {                  // If the amount[i] is                 // greater than 0                 if (amounts[i] > 0) {                     total += (amounts[i] - 1)                                  / mid                              + 1;                 }             }              // Update the ranges             if (total <= K) {                 high = mid;             }             else {                 low = mid;             }         }          cout << high << " ";          total = 0;          // Find the resultant string         for (int i = 0; i < 26; i++) {              if (amounts[i] > 0) {                 total += (amounts[i] - 1)                              / high                          + 1;                  for (int j = 0;                      j < ((amounts[i] - 1)                               / high                           + 1);                      j++) {                      // Generate the subsequence                     ans += char(i + 97);                 }             }         }          // If the length of resultant         // string is less than N than         // add a character 'a'         for (int i = total; i < K; i++) {             ans += 'a';         }          reverse(ans.begin(), ans.end());          // Print the string         cout << ans;     } }  // Driver Code int main() {     string S = "toffee";     int K = 4;     findString(S, K);      return 0; } 
Java
// Java code for above approach import java.util.*;  class GFG{  // Function to find the minimum number // of string required to generate // the original string static void findString(String S, int N) {        // Stores the frequency of each     // character of string S     int[] amounts = new int[26];      // Iterate over the range [0, 25]     for (int i = 0; i < 26; i++) {         amounts[i] = 0;     }      // Stores the frequency of each     // character of string S     for (int i = 0; i < S.length(); i++) {         amounts[(int)(S.charAt(i) - 97)]++;     }      int count = 0;      // Count unique characters in S     for (int i = 0; i < 26; i++) {         if (amounts[i] > 0)             count++;     }      // If unique characters is greater     // then N, then return -1     if (count > N) {         System.out.print("-1");     }      // Otherwise     else {          String ans = "";         int high = 100001;         int low = 0;         int mid, total;          // Perform Binary Search         while ((high - low) > 1) {              total = 0;              // Find the value of mid             mid = (high + low) / 2;              // Iterate over the range             // [0, 26]             for (int i = 0; i < 26; i++) {                  // If the amount[i] is                 // greater than 0                 if (amounts[i] > 0) {                     total += (amounts[i] - 1)                                  / mid                              + 1;                 }             }              // Update the ranges             if (total <= N) {                 high = mid;             }             else {                 low = mid;             }         }          System.out.print(high + " ");          total = 0;          // Find the resultant string         for (int i = 0; i < 26; i++) {              if (amounts[i] > 0) {                 total += (amounts[i] - 1)                              / high                          + 1;                  for (int j = 0;                      j < ((amounts[i] - 1)                               / high                           + 1);                      j++) {                      // Generate the subsequence                     ans += (char)(i + 97);                 }             }         }          // If the length of resultant         // string is less than N than         // add a character 'a'         for (int i = total; i < N; i++) {             ans += 'a';         }                  String reverse = "";          int Len = ans.length() - 1;               while(Len >= 0)               {                   reverse = reverse + ans.charAt(Len);                   Len--;               }           // Print the string         System.out.print(reverse);     } }  // Driver Code public static void main(String[] args) {     String S = "toffee";     int K = 4;     findString(S, K); } }  // This code is contributed by target_2. 
Python3
# Python3 program for the above approach   # Function to find the minimum number  # of string required to generate  # the original string  def findString(S, N):          # Stores the frequency of each      # character of String S      amounts = [0] * 26          # Stores the frequency of each      # character of String S      for i in range(len(S)):         amounts[ord(S[i]) - 97] += 1              count = 0          # Count unique characters in S      for i in range(26):         if amounts[i] > 0:             count += 1                  # If unique characters is greater      # then N, then return -1      if count > N:         print("-1")              # Otherwise      else:         ans = ""         high = 100001         low = 0                  # Perform Binary Search          while (high - low) > 1:             total = 0                          # Find the value of mid              mid = (high + low) // 2                          # Iterate over the range              # [0, 26]              for i in range(26):                                  # If the amount[i] is                  # greater than 0                  if amounts[i] > 0:                     total += (amounts[i] - 1) // mid + 1                                  # Update the ranges              if total <= N:                 high = mid             else:                 low = mid                          print(high, end = " ")         total = 0                  # Find the resultant string          for i in range(26):             if amounts[i] > 0:                 total += (amounts[i] - 1) // high + 1                 for j in range((amounts[i] - 1) // high + 1):                     ans += chr(i + 97)                  # If the length of resultant          # string is less than N than          # add a character 'a'                      for i in range(total, N):             ans += 'a'                      ans = ans[::-1]                  # Print the string          print(ans)  # Driver code S = "toffee" K = 4  findString(S, K)  # This code is contributed by Parth Manchanda 
C#
// C# program for the above approach using System;  class GFG{      // Function to find the minimum number // of string required to generate // the original string static void findString(string S, int N) {        // Stores the frequency of each     // character of string S     int[] amounts = new int[26];      // Iterate over the range [0, 25]     for (int i = 0; i < 26; i++) {         amounts[i] = 0;     }      // Stores the frequency of each     // character of string S     for (int i = 0; i < S.Length; i++) {         amounts[(int)(S[i] - 97)]++;     }      int count = 0;      // Count unique characters in S     for (int i = 0; i < 26; i++) {         if (amounts[i] > 0)             count++;     }      // If unique characters is greater     // then N, then return -1     if (count > N) {         Console.Write("-1");     }      // Otherwise     else {          string ans = "";         int high = 100001;         int low = 0;         int mid, total;          // Perform Binary Search         while ((high - low) > 1) {              total = 0;              // Find the value of mid             mid = (high + low) / 2;              // Iterate over the range             // [0, 26]             for (int i = 0; i < 26; i++) {                  // If the amount[i] is                 // greater than 0                 if (amounts[i] > 0) {                     total += (amounts[i] - 1)                                  / mid                              + 1;                 }             }              // Update the ranges             if (total <= N) {                 high = mid;             }             else {                 low = mid;             }         }          Console.Write(high + " ");          total = 0;          // Find the resultant string         for (int i = 0; i < 26; i++) {              if (amounts[i] > 0) {                 total += (amounts[i] - 1)                              / high                          + 1;                  for (int j = 0;                      j < ((amounts[i] - 1)                               / high                           + 1);                      j++) {                      // Generate the subsequence                     ans += (char)(i + 97);                 }             }         }          // If the length of resultant         // string is less than N than         // add a character 'a'         for (int i = total; i < N; i++) {             ans += 'a';         }                  string reverse = "";          int Len = ans.Length - 1;               while(Len >= 0)               {                   reverse = reverse + ans[Len];                   Len--;               }           // Print the string         Console.Write(reverse);     } }  // Driver Code public static void Main() {     string S = "toffee";     int K = 4;     findString(S, K); } }  // This code is contributed by splevel62. 
JavaScript
<script> // Javascript program for the above approach  // Function to find the minimum number // of string required to generate // the original string function findString(S, N) {    // Stores the frequency of each   // character of String S   let amounts = new Array(26);    // Iterate over the range [0, 25]   for (let i = 0; i < 26; i++) {     amounts[i] = 0;   }    // Stores the frequency of each   // character of String S   for (let i = 0; i < S.length; i++) {     amounts[S[i].charCodeAt(0) - 97]++;   }    let count = 0;    // Count unique characters in S   for (let i = 0; i < 26; i++) {     if (amounts[i] > 0) count++;   }    // If unique characters is greater   // then N, then return -1   if (count > N) {     document.write("-1");   }    // Otherwise   else {     let ans = "";     let high = 100001;     let low = 0;     let mid, total;      // Perform Binary Search     while (high - low > 1) {       total = 0;        // Find the value of mid       mid = Math.floor((high + low) / 2);        // Iterate over the range       // [0, 26]       for (let i = 0; i < 26; i++) {         // If the amount[i] is         // greater than 0         if (amounts[i] > 0) {           total += Math.floor((amounts[i] - 1) / mid + 1);         }       }        // Update the ranges       if (total <= N) {         high = mid;       } else {         low = mid;       }     }      document.write(high + " ");      total = 0;      // Find the resultant string     for (let i = 0; i < 26; i++) {       if (amounts[i] > 0) {         total += Math.floor((amounts[i] - 1) / high + 1);          for (let j = 0; j < Math.floor((amounts[i] - 1) / high + 1); j++) {           // Generate the subsequence           ans += String.fromCharCode(i + 97);         }       }     }      // If the length of resultant     // string is less than N than     // add a character 'a'     for (let i = total; i < N; i++) {       ans += "a";     }      ans =  ans.split("").reverse().join("");      // Print the string     document.write(ans);   } }  // Driver Code  let S = "toffee"; let K = 4; findString(S, K);  // This code is contributed by _saurabh_jaiswal. </script> 

Output: 
2 tofe

 

Time Complexity: O(N), where N is the length of the given string.
Auxiliary Space: O(K), for storing a string of length K.


Next Article
Minimize length of a string by removing occurrences of another string from it as a substring

S

samarpit_dua
Improve
Article Tags :
  • Strings
  • Searching
  • Mathematical
  • Hash
  • Game Theory
  • DSA
  • subsequence
  • frequency-counting
Practice Tags :
  • Game Theory
  • Hash
  • Mathematical
  • Searching
  • Strings

Similar Reads

  • Minimum length of the sub-string whose characters can be used to form a palindrome of length K
    Given a string str consisting of lowercase English letters and an integer K. The task is to find the minimum length of the sub-string whose characters can be used to form a palindrome of length K. If no such sub-string exists then print -1.Examples: Input: str = "abcda", k = 2 Output: 5 In order to
    14 min read
  • Minimize total cost of picking K unique subsequences from given string
    Given a string S of length N and a positive integer K, the task is to find the minimum total cost of picking K unique subsequence of the given string S such that the cost of picking a subsequence is the (length of S - length of that subsequence). If it is impossible to choose K unique subsequence, t
    8 min read
  • Minimize length of a string by removing occurrences of another string from it as a substring
    Given a string S and a string T, the task is to find the minimum possible length to which the string S can be reduced to after removing all possible occurrences of string T as a substring in string S. Examples: Input: S = "aabcbcbd", T = "abc"Output: 2Explanation:Removing the substring {S[1], ..., S
    8 min read
  • Minimum deletions to make String S the Subsequence of any String in the Set D
    Given a string S and a set of strings D, the task is to find the minimum number of deletions required to make the string S a subsequence of any string in the set D, such that the deletion can only be performed on the substring of S. Examples: Input: string S = "abcdefg", vector<string> D = {"a
    13 min read
  • Minimum cost for constructing the subsequence of length K from given string S
    Given a string S consisting of N lowercase English alphabets, and an integer K and, an array cost[] of size 26 denoting the cost of each lowercase English alphabet, the task is to find the minimum cost to construct a subsequence of length K from the characters of the string S. Examples: Input: S = "
    11 min read
  • All possible strings of any length that can be formed from a given string
    Given a string of distinct characters, print all possible strings of any length that can be formed from given string characters. Examples: Input: abcOutput: a b c abc ab ac bc bac bca cb ca ba cab cba acbInput: abcdOutput: a b ab ba c ac ca bc cb abc acb bac bca cab cba d ad da bd db abd adb bad bda
    10 min read
  • Lexicographically shortest string of length at most K which is not a substring of given String
    Given a string S, the task is to find the lexicographically shortest string of length less than or equal to K which is not a substring of the given string. If not possible, print -1. Examples: Input: S = zxabcehgf, K = 2Output: dExplanation: Lexicographically, the shortest string which is not a subs
    9 min read
  • Maximize the minimum length of K palindromic Strings formed from given String
    Given a string str of length N, and an integer K, the task is to form K different strings by choosing characters from the given string such that all the strings formed are palindrome and the length of the smallest string among the K strings is maximum possible. Examples: Input: str = "qrsprtps", K =
    10 min read
  • Minimize deletions in a Binary String to remove all subsequences of the form "0101"
    Given a binary string S of length N, the task is to find the minimum number of characters required to be deleted from the string such that no subsequence of the form “0101” exists in the string. Examples: Input: S = "0101101"Output: 2Explanation: Removing S[1] and S[5] modifies the string to 00111.
    6 min read
  • Generate an N-length string having longest palindromic substring of length K
    Given two integers N and K (K ? N), the task is to obtain a string of length N such that maximum length of a palindromic substring of this string is K. Examples: Input: N = 5, K = 3 Output: "abacd" Explanation: Palindromic substrings are "a", "b", "c", "d" and "aba". Therefore, the longest palindrom
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences