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:
Minimum days to achieve the String
Next article icon

Minimum cost to construct a string

Last Updated : 15 Feb, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a string s (containing lowercase letters only), we have to find the minimum cost to construct the given string. The cost can be determined using the following operations: 

  1. Appending a single character cost 1 unit 
  2. A sub-string of a new string(intermediate string) can be appended without any cost

Note* Intermediate string is the string formed so far. 

Examples: 

Input : "geks"
Output : cost: 4
Explanation:
appending 'g' cost 1, string "g"
appending 'e' cost 1, string "ge"
appending 'k' cost 1, string "gek"
appending 's' cost 1, string "geks"
Hence, Total cost to construct "geks" is 4Input : "abab"
Output : cost: 2
Explanation:
Appending 'a' cost 1, string "a"
Appending 'b' cost 1, string "ab"
Appending "ab" cost nothing as it
is substring of intermediate.
Hence, Total cost to construct "abab" is 2

Naive Approach: Check if there is a sub-string in the remaining string to be constructed which is also a sub-string in the intermediate string, if there is then append it at no cost and if not then append it at the cost of 1 unit per character.

In the above example when the intermediate string was "ab" and we need to construct "abab" then the remaining string was "ab". Hence there is a sub-string in the remaining string which is also a sub-string of intermediate string (i.e. "ab") and therefore costs us nothing.

Better Approach: We will use hashing technique, to maintain whether we have seen a character or not. If we have seen the character, then there is no cost to append the character and if not, then it cost us 1 unit. 

Now in this approach, we take one character at a time and not a string. This is because if "ab" is substring of "abab", so is 'a' and 'b' alone and hence make no difference. 
This also leads us to the conclusion that the cost to construct a string is never more than 26 in case the string contains all the alphabets (a-z). 

Implementation:

C++
#include <iostream> using namespace std;  int minCost(string& s) {     // Initially all characters are un-seen     bool alphabets[26] = { false };      // Marking seen characters     for (int i = 0; i < s.size(); i++)         alphabets[s[i] - 97] = true;      // Count total seen character, and that     // is the cost     int count = 0;     for (int i = 0; i < 26; i++)         if (alphabets[i])             count++;      return count; }  int main() {     // s is the string that needs to be constructed     string s = "geks";      cout << "Total cost to construct "          << s << " is " << minCost(s); // Corrected: call minCost with s      return 0; } 
Java
// Java Program to find minimum cost to // construct a string  class GFG  {      static int minCost(char[] s)      {                  // Initially all characters are un-seen         boolean alphabets[] = new boolean[26];          // Marking seen characters         for (int i = 0; i < s.length; i++)          {             alphabets[(int) s[i] - 97] = true;         }          // Count total seen character,          // and that is the cost         int count = 0;         for (int i = 0; i < 26; i++)         {             if (alphabets[i])              {                 count++;             }         }          return count;     }      // Driver code     public static void main(String[] args)      {         // s is the string that needs to be constructed         String s = "geeksforgeeks";         System.out.println("Total cost to construct " +                 s + " is " + minCost(s.toCharArray()));     } }  // This code is contributed by 29AjayKumar 
Python3
# Python 3 Program to find minimum cost to # construct a string  def minCost(s):          # Initially all characters are un-seen     alphabets = [False for i in range(26)]      # Marking seen characters     for i in range(len(s)):         alphabets[ord(s[i]) - 97] = True      # Count total seen character, and that     # is the cost     count = 0     for i in range(26):         if (alphabets[i]):             count += 1      return count  # Driver Code if __name__ == '__main__':          # s is the string that needs to      # be constructed     s = "geeksforgeeks"      print("Total cost to construct", s,                        "is", minCost(s))      # This code is contributed by # Surendra_Gangwar 
C#
// C# Program to find minimum cost to // construct a string using System;  class GFG  {      static int minCost(char[] s)      {                  // Initially all characters are un-seen         bool []alphabets = new bool[26];          // Marking seen characters         for (int i = 0; i < s.Length; i++)          {             alphabets[(int) s[i] - 97] = true;         }          // Count total seen character,          // and that is the cost         int count = 0;         for (int i = 0; i < 26; i++)         {             if (alphabets[i])              {                 count++;             }         }          return count;     }      // Driver code     public static void Main(String[] args)      {         // s is the string that          // needs to be constructed         String s = "geeksforgeeks";         Console.WriteLine("Total cost to construct " +                 s + " is " + minCost(s.ToCharArray()));     } }  // This code is contributed by Rajput-Ji 
JavaScript
<script>       // JavaScript Program to find minimum cost to       // construct a string       function minCost(s)       {                // Initially all characters are un-seen         var alphabets = new Array(26).fill(0);          // Marking seen characters         for (var i = 0; i < s.length; i++) {           alphabets[s[i].charCodeAt(0) - 97] = true;         }          // Count total seen character,         // and that is the cost         var count = 0;         for (var i = 0; i < 26; i++) {           if (alphabets[i]) {             count++;           }         }          return count;       }        // Driver code       // s is the string that       // needs to be constructed       var s = "geeksforgeeks";       document.write(         "Total cost to construct " + s + " is " + minCost(s.split(""))       );              // This code is contributed by rdtank.     </script> 

Output
Total cost to construct geeksforgeeks is 1 

Time Complexity: O(n)
Auxiliary Space: O(1)
 


Next Article
Minimum days to achieve the String
author
shubham_rana_77
Improve
Article Tags :
  • Strings
  • Hash
  • DSA
Practice Tags :
  • Hash
  • Strings

Similar Reads

  • Minimum cost to modify a string
    Given string str consisting of lower case alphabets only and an integer K. The task is to find the minimum cost to modify the string such that the ASCII value difference between any two characters of the given string is less than equal to K. The following operations can be performed on the string: I
    15+ min read
  • Minimum cost to convert string into palindrome
    Convert string S into a palindrome string. You can only replace a character with any other character. When you replace character 'a' with any other character, it costs 1 unit, similarly for 'b' it is 2 units ..... and for 'z', it is 26 units. Find the minimum cost required to convert string S into p
    4 min read
  • Minimum clicks to convert string X to Y
    Given a starting string X of 3 characters, finishing string Y of 3 characters and an array of forbidden strings. The task is to find the minimum number of clicks to reach Y from X. Rules: Each of the 3 characters changes in a circular manner i.e. on each click you can go from either a to b or a to z
    15+ min read
  • Minimum days to achieve the String
    Given a string S of length N containing only lowercase alphabets, also given a permutation P of length N containing integers from 0 to N-1. In (i+1)th day you can take the P[i] value of the permutation array and replace S[P[i]] with a '?'. For example on day 1, we can choose the index of the permuta
    15+ min read
  • Minimum cost to make two strings same
    Given four integers a, b, c, d and two strings S1 and S2 of equal length, which consist only of the characters '2', '1' and '0'. Converting '1' to '2' or vice versa costs a.Converting '2' to '3' or vice versa costs b.Converting '3' to '1' or vice versa costs c.Deleting the ith character from both th
    7 min read
  • Minimum insertion to make consecutive 'XYZ' substrings
    Given string S consisting of characters 'X', 'Y' and 'Z' only. The your task is to find minimum number of operations required to make string containing only consecutive "XYZ" substrings given that you are allowed to choose any one out of three characters and insert it anywhere in S. Examples: Input:
    5 min read
  • Minimum insertions to form a palindrome
    Given a string s, the task is to find the minimum number of characters to be inserted to convert it to a palindrome. Examples: Input: s = "geeks"Output: 3Explanation: "skgeegks" is a palindromic string, which requires 3 insertions. Input: s= "abcd"Output: 3Explanation: "abcdcba" is a palindromic str
    15+ min read
  • Minimum Cost To Make Two Strings Identical
    Given two strings X and Y, and two values costX and costY. We need to find minimum cost required to make the given two strings identical. We can delete characters from both the strings. The cost of deleting a character from string X is costX and from Y is costY. Cost of removing all characters from
    11 min read
  • Count the minimum number of groups formed in a string
    Given a string 'S' which comprises two or more uppercase English letters. The task is to count the minimum number of groups required to completely cover the string by replacing consecutive characters with the same single character. Examples: Input : S = "TTWWW"Output : 2Explanation : There are 2 gro
    7 min read
  • Minimum cost to make a string free of a subsequence
    Given string str consisting of lowercase English alphabets and an array of positive integer arr[] both of the same length. The task is to remove some characters from the given string such that no sub-sequence in the string forms the string "code". Cost of removing a character str[i] is arr[i]. Find
    6 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