VOOZH about

URL: https://www.geeksforgeeks.org/dsa/convert-given-string-to-another-by-minimum-replacements-of-subsequences-by-its-smallest-character/

⇱ Convert given string to another by minimum replacements of subsequences by its smallest character - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Convert given string to another by minimum replacements of subsequences by its smallest character

Last Updated : 7 Aug, 2023

Given two strings A and B, the task is to count the minimum number of operations required to convert the string A to B. In one operation, select a subsequence from string A and convert every character of that subsequence to the smallest character present in it. If it is not possible to transform, then print "-1".

Examples:

Input: A = "abcab", B = "aabab" 
Output:
Explanation:
Operation 1: Replacing characters from indices {2, 1} by the smallest character from those indices(i.e. 'b'), transforms A to "abbab". 
Operation 2: Replacing characters from indices {1, 0}, by the smallest character from those indices(i.e. 'a'), transforms A to "aabab". 
Therefore, the count of operations required to convert string A to B is 2.

Input: A = "aaa", B = "aab" 
Output: -1 
Explanation:
There is no possible way to convert A to B as string A doesn't contain 'b'.

Approach: The approach is based on the idea that if any character at index i of string A is less than the character at index i of string B, then it is impossible to change A to B because changing a character to a character smaller than itself is not allowed.

Below is the implementation of the above approach:


Output
2

Time Complexity: O(N) 
Auxiliary Space: O(N)

Comment