CodingNodes / 2-D Dynamic Programming / Interleaving String System design Space play · ←→ step · R restart

Problem

Given three strings s1, s2 and s3, decide whether s3 can be formed by weaving the letters of s1 and s2 together.

Weaving means every letter of s1 and of s2 is used exactly once, and the letters of each string stay in their original relative order, though letters from the two strings may alternate in any pattern. Return true if such a weave gives s3.

Constraints

  • 0 ≤ s1.length, s2.length ≤ 100
  • 0 ≤ s3.length ≤ 200
  • all strings use lowercase English letters

Examples: pick one to animate

Solutions

TimeO(m · n) SpaceO(m · n)

Time: The table has (m + 1) · (n + 1) cells and each one checks two neighbours in constant time.

Space: The full table of booleans is stored.

If the lengths do not add up to s3, stop. Otherwise let dp[i][j] say whether the first i letters of s1 and the first j of s2 can weave the first i + j letters of s3. The last letter came either from s1 (look at the cell above) or from s2 (look at the cell to the left), and it must equal the matching letter of s3.