• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
July 07, 2022 |6.4K Views
Minimum cost to construct a string
  Share   Like
Description
Discussion

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.

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). 


Minimum cost to construct a string : https://www.geeksforgeeks.org/minimum-cost-construct-string/