Interleaving String solution explained

Interleaving String asks whether a target string can be built by merging two other strings while keeping each one's letters in their original order. Solve it with dynamic programming on two indexes: cell (i, j) records whether the first i letters of one string and the first j of the other can produce the first i + j letters of the target. That is O(m·n) time, and one reused row brings the memory down to O(n).

By Published 10 min read

The problem, reworded

You get three strings: a, b and target. Picture dealing cards from two face-up piles onto one row. At each step you may take the next letter from a or the next letter from b, but never skip ahead within a pile. The question is whether some sequence of choices produces exactly the target, using every letter of both piles. Return true or false.

Strings made up for this page, with answers from the code below
abtargetAnswerWhy
cabcodccaobdtruec from a, c from b, a, o, b, d
cabcodcocabdtrueTake c and o from b first, then all of a, then d
cabcodcadbcofalseThe d appears before b's o, which breaks b's order
abcabcdfalseLengths differ, so no merge can match
(empty)okoktrueWith one pile empty, the target must equal the other pile
Strings made up for this page, with answers from the code below. Scroll sideways on a small screen.

Two clarifying questions are worth asking. First, are the letters limited to lowercase English, or can they be any characters? It changes nothing in the algorithm, but it shows you read the constraints. Second, some versions of the prompt describe the merge as alternating blocks from each string. Since a block may be a single letter, that wording allows exactly the same results as letter-by-letter dealing, so the solution below covers both.

Why interviewers like it

This problem looks like a string puzzle and is really a test of whether you can spot overlapping subproblems. Many candidates start with two pointers and a greedy rule, hit a failing case, then patch the rule. The interviewer is waiting for the moment you say: the state is just how many letters I have used from each string, and there are only (m + 1)(n + 1) such states. Once you say that, the rest is bookkeeping.

Why a greedy merge breaks

The tempting rule is: walk the target, and take the letter from a when a's next letter matches, otherwise from b. Try a = m, b = mo and target = mom. The greedy rule takes the first m from a. Now it needs o, but a is empty and b still starts with m, so it reports false. The right answer is true: take m and o from b, then the m from a. Whenever both piles offer the same letter, either choice might be the one that works, and you cannot tell until later. That is the signal to stop guessing and search every choice, with caching.

Brute force: try both piles, then cache

Write a function go(i, j) that answers: having used i letters of a and j letters of b, can the rest be finished? The next target position is always i + j, so the target index is not part of the state. If a[i] matches it, try go(i + 1, j); if b[j] matches it, try go(i, j + 1). With no cache, repeated letters make the two branches split again and again, which is exponential in the worst case, up to roughly 2 to the power of the target's length.

The same (i, j) pair is reached by many different paths, though. Caching the result for each pair means each of the (m + 1)(n + 1) states is solved once, with constant work per state.

from functools import lru_cache

def can_weave_memo(a, b, target):
    if len(a) + len(b) != len(target):
        return False

    @lru_cache(maxsize=None)
    def go(i, j):
        if i == len(a) and j == len(b):
            return True
        k = i + j
        if i < len(a) and a[i] == target[k] and go(i + 1, j):
            return True
        return j < len(b) and b[j] == target[k] and go(i, j + 1)

    return go(0, 0)
Top-down: recursion on (i, j) with a cache. O(m·n) time and space.

This version is a fine interview answer on its own. Its weakness is recursion depth: a long target can exceed Python's default recursion limit, which is one reason to know the bottom-up table too.

Bottom-up: fill the grid

Turn the cache into a table. Cell ok[i][j] is true when the first i letters of a and the first j letters of b can be merged into the first i + j letters of target. The empty prefixes make an empty target, so ok[0][0] is true. A cell can be reached from above, by placing a's i-th letter last, or from the left, by placing b's j-th letter last. Either move is allowed only if that letter equals target[i + j - 1].

def can_weave_table(a, b, target):
    if len(a) + len(b) != len(target):
        return False
    # ok[i][j]: the first i letters of a and the first j of b
    # can produce the first i + j letters of target
    ok = [[False] * (len(b) + 1) for _ in range(len(a) + 1)]
    ok[0][0] = True
    for i in range(len(a) + 1):
        for j in range(len(b) + 1):
            if i > 0 and ok[i - 1][j] and a[i - 1] == target[i + j - 1]:
                ok[i][j] = True
            if j > 0 and ok[i][j - 1] and b[j - 1] == target[i + j - 1]:
                ok[i][j] = True
    return ok[len(a)][len(b)]
Python: the full (m + 1) × (n + 1) table.

The grid for a = ten, b = tin, target = tetinn

Rows are letters used from a, columns are letters used from b. T means reachable. Computed by the code above.
j = 0j = 1 (t)j = 2 (i)j = 3 (n)
i = 0TT..
i = 1 (t)T...
i = 2 (e)TTTT
i = 3 (n)..TT
Rows are letters used from a, columns are letters used from b. T means reachable. Computed by the code above.. Scroll sideways on a small screen.

Read it as paths from the top-left corner to the bottom-right, moving down for a letter of a and right for a letter of b. One valid path is down, down, right, right, down, right: t and e from a, t and i from b, then a's n and b's n. The bottom-right cell is T, so the answer is true. Note the dead cell at (1, 1): one t from each string spells tt, but the target begins te, so neither move into that cell fits.

One row is enough

Each cell reads only the cell above it and the cell to its left. So keep a single row. When you are about to overwrite row[j], it still holds the value from the previous row, which is the cell above, and row[j - 1] has already been updated, which is the cell to the left. Memory drops to O(n). If you want the smaller of the two lengths, swap a and b first so the row follows the shorter string.

def can_weave(a, b, target):
    if len(a) + len(b) != len(target):
        return False
    row = [False] * (len(b) + 1)  # one row of the table, reused
    for i in range(len(a) + 1):
        for j in range(len(b) + 1):
            if i == 0 and j == 0:
                row[j] = True
                continue
            from_a = i > 0 and row[j] and a[i - 1] == target[i + j - 1]
            from_b = j > 0 and row[j - 1] and b[j - 1] == target[i + j - 1]
            row[j] = from_a or from_b
    return row[len(b)]
Python: one reused row. O(m·n) time, O(n) extra space.
function canWeave(a, b, target) {
  if (a.length + b.length !== target.length) return false;
  const row = new Array(b.length + 1).fill(false);
  for (let i = 0; i <= a.length; i++) {
    for (let j = 0; j <= b.length; j++) {
      if (i === 0 && j === 0) {
        row[j] = true;
        continue;
      }
      const fromA = i > 0 && row[j] && a[i - 1] === target[i + j - 1];
      const fromB = j > 0 && row[j - 1] && b[j - 1] === target[i + j - 1];
      row[j] = fromA || fromB;
    }
  }
  return row[b.length];
}
JavaScript: the same rolling row.

Complexity

m = length of a, n = length of b
ApproachTimeExtra space
Plain recursion, no cacheExponential in the worst caseO(m + n) for the call stack
Recursion with a cacheO(m·n)O(m·n) cache plus the call stack
Full tableO(m·n)O(m·n)
One reused rowO(m·n)O(min(m, n)) after swapping so the row is the shorter string
m = length of a, n = length of b. Scroll sideways on a small screen.

Edge cases

  • Length mismatch: if len(a) + len(b) differs from len(target), return false before building anything. Without this check, index arithmetic can read past the end of the target.
  • One or both strings empty: the table still works, since row 0 and column 0 handle a single pile.
  • All three strings empty: true, because merging nothing gives nothing.
  • Heavy repetition, such as strings made only of the letter x: this is where plain recursion blows up and the cache earns its keep.
  • Same letters, wrong counts: if target has three x's but a and b hold only two between them, the length check or the table will reject it.

Mistakes that cost points

  • Using a greedy merge and patching it with special cases. It looks close and keeps failing on new inputs.
  • Adding the target index as a third state dimension. It is always i + j, so a third dimension just multiplies the work.
  • Off-by-one errors in target[i + j - 1]. Say aloud that cell (i, j) covers prefixes of length i and j, so the last placed letter sits at index i + j - 1.
  • In the one-row version, forgetting the first column. For j = 0 only the move from above is possible, and the code must still recompute it on every row instead of keeping a stale value.
  • Checking only that the letter counts match. Counts can agree while the order is impossible, as in the third example above.

Follow-up questions

  • Show one valid merge, not just true or false. Keep the full table, then walk back from the bottom-right corner, choosing any neighbor that is true and whose letter matches.
  • Count the number of distinct ways. Store counts instead of booleans and add the two incoming counts. Different paths can spell the same target, so be clear whether you count paths or distinct labelings.
  • Three source strings. The state becomes (i, j, k) and the cost grows to the product of all three lengths.
  • Breadth-first search instead of a table. Treat each (i, j) as a node and explore only reachable states. It visits the same states in the worst case but can stop early on easy inputs.

How to explain it out loud

Fictional example

A short spoken version
Candidate
A greedy merge fails when both strings offer the same next letter, because I can't know which one to use yet. So I'll treat it as a search over choices.
Candidate
The only state that matters is how many letters I've used from each string. The target position is their sum, so there are about m times n states.
Candidate
Cell (i, j) is true if I can arrive from above with a matching letter of a, or from the left with a matching letter of b. Each cell needs only its upper and left neighbors, so one row is enough, which gives O(m·n) time and O(n) space.

Jump Game starts from a similar table of reachable positions, then shows how a greedy rule can replace it when the choices never conflict. Jump Game II is the minimum-moves version of that problem. For another search over choices that only keeps going while the string can still be completed, see Generate Parentheses. Everything is listed on the coding problems hub.

Using Natively while you practice

On a Mac or a Windows PC, Natively can take a screenshot of this prompt during a practice session and help you think through why the state is two indexes and not three. Natively also transcribes your mock interview and saves notes, so afterward you can check whether you described the table's meaning before writing loops. More detail is on the AI interview assistant page.

Questions people ask

How do you solve Interleaving String?

Use dynamic programming where cell (i, j) says whether the first i letters of one string and the first j of the other can form the first i + j letters of the target. A cell is true if the cell above or to the left is true and the letter placed last matches.

Why doesn't a two-pointer greedy work for Interleaving String?

When both strings offer the same next letter, the greedy has to guess. A wrong guess only fails later, as with a = m, b = mo and target mom, where taking the first m from a leads to a dead end.

What is the time and space complexity of Interleaving String?

O(m·n) time for m and n letters in the two source strings. The full table uses O(m·n) space; keeping one row cuts that to O(n), or to the shorter length if you swap the strings.

What is the first check in Interleaving String?

Compare lengths. If the two source strings together are not exactly as long as the target, the answer is false and no table is needed.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP