Friday, August 25th
Interwoven strings
Given three strings, determine if the third string can be formed by interleaving the first two strings
The overlapping nature of the subproblems suggest a dynamic programming approach. This problem is also similar to the longest common subsequence. We will approach this problem in a top-down manner.
Declare a 2-dimensional array as a global variable. The 2 state variables are the indices to string 1 and string 2. This will be our memo
To reduce the number of parameters to our dp function, we also declare the 3 strings as global variables
In the main function, first check that the length of string 1 and 2 equal the length of string 3. If not, then the answer is false.
Otherwise, initialize the memo to the dimensions of the length of string 1+1 and the length of string 2+1, with a default value of -1. Also set the global strings equal to the strings that are input
End the main function with a call to the dp function, which will return the result when the indices to string s1 and s2 are at 0
Now we define our dp function
bool dp(int i1,int i2) {
...
}
For recursion, we first begin with our halting condition. If the two indices add up to the size of string 3, then we have successfully found an interwoven string
Otherwise, if the memo for the two indices is not equal to -1, return the answer
if(memo[i1][i2]!=-1) return memo[i1][i2];
Now for the important part, the recurrence relation - using the indices to s1 and s2, check if the index to part of s1 equals apart of s3 at the index of s1+s2, and if so, call recursively call dp while incrementing the index to string 1. Do the same for string 2. Mind the size of the indices
Record the answer in the memo and return it
Straight forward 2-state dynamic programming, similar to longest common subsequence, which is a fundamental DP problem. A solid medium difficulty
Thanks to the Editorial and Solutions for clearing up the recurrence relation
Comments
Post a Comment