VOOZH about

URL: https://www.geeksforgeeks.org/dsa/minimize-set-cost/

⇱ Minimize Set Cost - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Minimize Set Cost

Last Updated : 28 Jan, 2024

Given a string s of size n. In one move you can take any subsequence of the given string and add it to the set S. The set S can't contain duplicates. The move costs nāˆ’|t|, where |t| is the length of the added subsequence. The task is to find out the minimum possible total cost to obtain a set S of size k.

Example:

Input: n = 4, k = 5, s = "asdf"
Output: 4

Input: n = 5, k = 6, s = aaaaa
Output: 15

Approach:

This problem can be approached using Breadth-First Search (BFS). Consider each string as a vertex in the graph, and there exists a directed edge from string s to string t if and only if t can be obtained from s by removing exactly one character.

In this context, the goal is to find the first k visited vertices when starting the BFS from the initial string. The minimum total cost is then calculated as nk minus the sum of the lengths of the visited strings. It is essential to use a queue of strings instead of integers for BFS, and maintain a set of visited strings instead of an array of visited vertices. The BFS process should terminate when exactly k strings are obtained.

If the number of distinct subsequences is less than k, the answer is -1.

Follow the steps to solve the above problem:

  • Initialize the variable ans to 0.
  • Create a queue of strings (q) for BFS.
  • Create a set of strings (st) to keep track of visited strings.
  • Push the initial string s to the queue and mark it as visited in the set.
  • Breadth-First Search (BFS):
    • While the queue is not empty and the set size is less than k:
      • Pop the front string (v) from the queue.
      • For each character in the string:
        • Create a new string by removing the character.
        • If the new string is not visited and the set size is less than k:
          • Push the new string to the queue, mark it as visited, and update ans.
  • If the set size is less than k, output -1.
  • Otherwise, output the final value of ans.

Below is the implementation of the above approach:


Output
4

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

Comment
Article Tags: