The Interleaving String interview question asks if a string s3 can be formed by "interleaving" two other strings, s1 and s2. Interleaving means that the relative order of characters from both s1 and s2 is preserved, and every character from both is used exactly once to form s3.
Companies like Goldman Sachs, Google, and Amazon use the Interleaving String coding problem to test a candidate's knowledge of Dynamic Programming. While a simple recursion seems intuitive, it leads to an exponential search space. This problem evaluations whether you can identify overlapping subproblems and use memoization or a 2D table to solve it in time.
This is a classic 2D Dynamic Programming problem.
dp[i][j] is a boolean indicating if s3[0...i+j-1] can be formed by interleaving s1[0...i-1] and s2[0...j-1].dp[0][0] = true (empty strings).s1[i-1] == s3[i+j-1], then dp[i][j] = dp[i-1][j].s2[j-1] == s3[i+j-1], then dp[i][j] = dp[i][j] || dp[i][j-1].
This builds the answer from the ground up by checking if the current character of s3 could have come from either s1 or s2.s1 = "aab", s2 = "db", s3 = "aadbb"
dp[1][0]: s3[0] is 'a', s1[0] is 'a'. Match! dp[1][0] = true.dp[2][0]: s3[1] is 'a', s1[1] is 'a'. Match! dp[2][0] = true.dp[2][1]: s3[2] is 'd', s2[0] is 'd'. Match! dp[2][1] = true.dp[length1][length2], the answer is true.s1.length + s2.length == s3.length at the very beginning.visited or memo table.Practice reducing 2D DP to 1D DP. For this problem, you only need the previous row of the DP table, allowing you to optimize space from to . This is a high-level String interview pattern skill.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Decode Ways | Medium | Solve | |
| Longest Palindromic Subsequence | Medium | Solve | |
| Edit Distance | Medium | Solve | |
| Longest Common Subsequence | Medium | Solve | |
| Delete Operation for Two Strings | Medium | Solve |