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

vector<vector<int> > memo;

To reduce the number of parameters to our dp function, we also declare the 3 strings as global variables

    string s1, s2, s3;

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.  

bool isInterleave(string s1, string s2, string s3) {
if(s1.size()+s2.size()!=s3.size()) return 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

memo=vector<vector<int> >(s1.size()+1, vector<int>(s2.size()+1, -1));
this->s1=s1;
this->s2=s2;
this->s3=s3;

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

return dp(0,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

if(i1+i2==s3.size()) return 1;

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

 bool ans=false;
    if(i1<s1.size() && s1[i1]==s3[i1+i2])
ans=(ans | dp(i1+1,i2) );
if(i2<s2.size() && s2[i2]==s3[i1+i2])
ans=(ans | dp(i1,i2+1));

Record the answer in the memo and return it

return memo[i1][i2]=ans;

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

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th