Minimum cost to construct a string

08 Feb, 2022
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 costNote* 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 4

Input :  "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).  
C++
Java
Python3
C#
Javascript
// C++ Program to find minimum cost to// construct a string#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 = "geeksforgeeks";     cout << "Total cost to construct "         << s << " is " << minCost;     return 0;}
// 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
# 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 Codeif __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# Program to find minimum cost to// construct a stringusing 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
<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 7
 
Minimum cost to construct a string | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersMinimum cost to construct a string | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:34•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=pvhWm7zhgGg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
 
29AjayKumar
Rajput-Ji
SURENDRA_GANGWAR
rdtank
chhabradhanvi
Hash
Strings
Hash
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Longest Consecutive Subsequence
Counting frequencies of array elements
Sorting a Map by value in C++ STL
Print Nodes in Top View of Binary Tree
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++