CodeArchon

medium2-D Dynamic ProgrammingMicrosoft

Weave Checker

A merge-sort tool verifies whether a long string could have been produced by interleaving two shorter strings while preserving each one's order.

Given strings s1, s2, s3, return true iff s3 is a valid interleaving of s1 and s2 (preserving order).

Choose approach

T
F
F
F
F
F
row
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
?
1/7
Narrationstep 1 of 7

Row 0 filled (used s1[0..-1]).

1def isInterleave(s1, s2, s3):
2 if len(s1) + len(s2) != len(s3): return False
3 m, n = len(s1), len(s2)
4 dp = [[False]*(n+1) for _ in range(m+1)]
5 dp[0][0] = True
6 for i in range(m+1):
7 for j in range(n+1):
8 if i > 0 and dp[i-1][j] and s1[i-1] == s3[i+j-1]: dp[i][j] = True
9 if j > 0 and dp[i][j-1] and s2[j-1] == s3[i+j-1]: dp[i][j] = True
10 return dp[m][n]
Variables
i=0

How to think about it

  1. Length check first.
  2. Each dp[i][j] has at most 2 incoming transitions.

Edge cases to catch in interview

  • Empty s1, s2, s3 -> true.
  • Length mismatch -> false.

Examples

Example 1true
{"s1":"","s2":"","s3":""}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed