
Input: ‘N’ = 3, ‘M’ = 3, ‘A’ = aba, ‘B’ = aab
Output: 3
One of the valid strings with minimum cost after merging ‘A’ and ‘B’ is ‘aaabba’. The order of characters of string ‘A’ as well as ‘B’ is maintained in the string ‘aaabba’ and the cost of this string is (1 + 2) = 3.
The first line will contain the integer 'T', denoting the number of test cases.
The first line of each test case contains two integers ‘N’ and ‘M’ denoting the length of strings ‘A’ and ‘B’ respectively’.
The second line of each test case contains the string ‘A’.
The third line of each test case contains the string ‘B’.
For each test case, you don’t need to print anything just return the minimum cost of merging strings ‘A’ and ‘B’.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 5000
1 <= M <= 5000
Sum of N Over all the Test cases <= 5000
Sum of M Over all the Test cases <= 5000
Time Limit: 1 sec
In this approach, We can recursively merge the strings. Since we need to merge the strings in such a way that their relative order is maintained, we can have two pointers ‘AIDX’ and ‘BIDX’ pointing to the first characters of strings ‘A’ and ‘B’ respectively. At any point, we have two options, either we merge the character at ‘A[ AIDX ]’ or we merge the character at ‘B[ BIDX ]’.
We can recursively try both ways one by one and check which one yields the minimum cost. To check the number of consecutive characters that are not equal we can make a variable that denotes the last character was taken from which string and then we can access the character and check if the current merging character is equal to the previous character or not.
// Recursive function to find minimum cost
The backtracking approach discussed before can be optimized using memoization. Let a state ‘S’ be defined by (‘AIDX’, ‘BIDX’, ‘lastCh’), if we observe carefully we are calculating the minimum value for some states (‘AIDX’, ‘BIDX’, ‘lastCh’) many times. We can store the minimum value for each state ‘S’ in a matrix and when we visit it again we will not calculate it but return the value already stored,
Let us define a matrix ‘DP’ of size ‘N’ x ‘M’ x 2. 2 is used as an identifier to detect the last character was taken from which string. ‘DP[ i ][ j ][ k ]’ stores the minimum value calculated for the state ( ‘i’, ‘j’, ‘k’ ).
// Recursive function to find minimum cost
The idea is the same as memoization. We are going to use the recurrence relation used in memoization.