![]() |
VOOZH | about |
Given two strings A and B of size N and M respectively, where B is a sub-sequence of A and an array arr[] of size N, where arr[i] is the cost to delete ith character from string A. The task is to find the minimum cost to delete characters from A such that after deletion no subsequence of A is the same as B.
Examples:
Input: A = "abccd", B = "ccd", arr[] = {1, 2, 3, 4, 5}
Output: 3
Explanation: If we remove either 'd' or a single 'c' from A then it will not be possible to construct a sub-sequence equals to B.
Among these the cost to remove the 'c' at index 2 is minimum that is 3. So the answer is 3.Input: A = "abccdabccdabccd", B = "bccd", arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
Output: 21
Explanation: If we remove the three 'b's with cost 2, 7 and 5, then A becomes "accdaccdaccd".
Now there is no way to construct a sub-sequence = "bccd"
Approach: The naive approach to solve the problem is to use recursion and to find a common subsequence between A and B as per the following idea:
If the character of A and B matches there will be 2 options: either remove that character from A or keep that character and remove other characters.
Follow the steps mentioned below to implement the idea:
Time Complexity: O(2M)
Auxiliary Space: O(1)
Efficient Approach: The time of the above approach can be further optimized using Dynamic Programming as per the following idea:
Use a 3D dp[][][] array to store the minimum cost until a given position in A and B and for removing at least one character. dp[i][j][] stores minimum cost to delete characters till ith index of A and jth index of B where either at least one character is deleted or not.
Hence the third dimension only has two value either 1 (at least one is deleted) or 0 (none is deleted)
Below is the implementation of the above approach.
21
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
Iterative approach : Using DP Tabulation method
The approach to solve this problem is same but DP tabulation(bottom-up) method is better then Dp + memorization(top-down) because memorization method needs extra stack space of recursion calls.
Steps to solve this problem :
Implementation :
Output:
21
Time complexity: O(n*m^2)
Auxiliary Space: O(n*m^2)