Interleaving String

Difficulty: Medium

Given three strings s1, s2 and s3, decide whether s3 can be formed by interleaving s1 and s2, keeping each string's characters in their original order.

It's like riffle-shuffling two decks of cards: each deck keeps its own order, but the two decks get mixed together.

Examples

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

Input: s1 = "", s2 = "", s3 = ""
Output: true

Constraints

  • 0 <= s1.length, s2.length <= 100

  • 0 <= s3.length <= 200

  • All three strings contain only lowercase English letters

Approach

Cell (i, j) answers: can the first i + j characters of s3 be built from the first i characters of s1 and the first j of s2? Every character of s3 comes from one of the two strings, so the position in s3 is always i + j — no need to track it separately.

Cell (i, j) is true if either:

  • (i-1, j) is true and the next character of s1 matches the next one needed in s3, or
  • (i, j-1) is true and the next character of s2 matches.

The base case (0, 0) is true (empty prefixes match an empty result), and the answer is the bottom-right corner, (len(s1), len(s2)).

Solutions

Brute Force — Recursion

Track how far into s1 and s2 you are (their sum is your position in s3). Take the next character from s1 or s2 if it matches, and recurse. This reaches the same (i, j) pair through many paths.

function isInterleave(s1, s2, s3) {
  if (s1.length + s2.length !== s3.length) return false;

  function solve(i, j) {
    const k = i + j;
    if (i === s1.length && j === s2.length) return true;

    let ok = false;
    if (i < s1.length && s1[i] === s3[k]) ok = solve(i + 1, j);
    if (!ok && j < s2.length && s2[j] === s3[k]) ok = solve(i, j + 1);
    return ok;
  }

  return solve(0, 0);
}

Time: O(2^(m + n)) in the worst case · Space: O(m + n) — recursion depth

Optimal — Bottom-Up 2D Table

Build a boolean table over (prefix length of s1, prefix length of s2), filling it from the top-left base case using cells already computed.

function isInterleave(s1, s2, s3) {
  const m = s1.length;
  const n = s2.length;
  if (m + n !== s3.length) return false;

  const table = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(false));
  table[0][0] = true;

  for (let i = 0; i <= m; i++) {
    for (let j = 0; j <= n; j++) {
      if (i === 0 && j === 0) continue;

      const k = i + j - 1; // index into s3 of the character just placed
      let ok = false;
      if (i > 0 && table[i - 1][j] && s1[i - 1] === s3[k]) ok = true;
      if (!ok && j > 0 && table[i][j - 1] && s2[j - 1] === s3[k]) ok = true;
      table[i][j] = ok;
    }
  }

  return table[m][n];
}

Time: O(m * n) · Space: O(m * n)