Interleaving Strings
Let's solve the Interleaving Strings problem using Dynamic Programming.
Statement
Given strings s1
, s2
, and s3
, find whether an interleaving of s1
and s2
forms s3
.
An interleaving of two strings a and b is a configuration where a and b splits into and substrings, respectively, such that:
- a + + … +
- b + + … +
- The interleaving can follow either of the following two formats:
- can be a consecutive sequence of characters in string
s1
. - can be a consecutive sequence of characters in string
s2
.
Note: is the concatenation of the strings and .
Let’s say we have two strings, “abc” and “xyz”. We may interleave them in multiple ways. We may alternately pick one character from each string until we have used up all the characters, giving us “axbycz” and “xaybzc”. Or, we may try to pick two characters at a time from each string, giving us “abxycz” and “xyabzc”. If we pick three characters at a time, we get “abcxyz” and “xyzabc”. Another class of variations is to pick a variable number of characters from each string, which leads to many more possibilities, such as “abxcyz”, “xayzbc”, and so on. However, “bxaycz” is not a valid interleaving, as the order of the characters taken from the first string is not preserved, since “b” appears here before “a”. Similarly, “acxybz” is not a valid interleaving.
Constraints:
-
s1.length
,s2.length
-
s3.length
s1
,s2
, ands3
consist of lowercase English letters.
Examples
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.