15% off all plans & roadmaps Use code

See plans

Interleaving String

Updated

TL;DR: Decide whether s3 can be built by weaving s1 and s2 together while keeping each string's order. Track how many characters you took from each string as a grid cell (i, j) and fill the grid with DP in O(n * m) time.

Problem

You are given three strings s1, s2 and s3. Decide whether s3 can be built by interleaving s1 and s2.

An interleaving keeps the left-to-right order of the characters taken from s1, and separately keeps the order of the characters taken from s2. At each position, the next character of s3 comes from one of the two strings.

Every character of both s1 and s2 must be used exactly once, so s3 must have length s1.length + s2.length. Return true if at least one valid interleaving produces s3, otherwise return false.

Example 1

Input: s1 = "cat", s2 = "dog", s3 = "cdoatg"
Output: true
Explanation: Take c from s1, then d and o from s2, then a and t from s1, and finally g from s2.

Example 2

Input: s1 = "ab", s2 = "ba", s3 = "bbaa"
Output: false
Explanation: After taking b from s2, the next b cannot come from either string. s2 must continue with a, and s1 starts with a.

Example 3

Input: s1 = "", s2 = "hello", s3 = "hello"
Output: true
Explanation: When s1 is empty, the only interleaving uses all of s2, which matches s3 exactly.

Constraints

  • 0 <= s1.length <= 100
  • 0 <= s2.length <= 100
  • 0 <= s3.length <= 200
  • s1, s2 and s3 contain only lowercase English letters
  • s3.length = s1.length + s2.length

Constraints that matter

  • s1 and s2 are at most 100 characters each, so the number of (i, j) states is at most 101 * 101 = 10,201. A table over all states is tiny, and an O(n * m) solution runs instantly.
  • Each step has up to two choices, so the unmemoized search can reach 2^200 paths. That is far beyond any time limit and forces you to cache states.
  • s3.length equals s1.length + s2.length is stated, but you should still check it first. It makes the index i + j safe and ends many inputs in constant time.
  • Only lowercase letters appear, so no special encoding is needed. Comparing characters directly is enough.
  • s1 and s2 may be empty. Your table and loops must handle row 0 and column 0 without reading index -1.

View on LeetCode

Hints

Hint 1

This is a 2D dynamic programming problem on a grid.

Hint 2

Try every way to build s3.

Solution

Intuition

This is a 2D dynamic programming problem on a grid. After you have used i characters of s1 and j characters of s2, you have written exactly i + j characters of s3. So the pair (i, j) fully describes where you are. Nothing else about the history matters.

Picture one row of mailboxes you repaint as you walk down a street, with the array dp as that row. Each box keeps its old label until you overwrite it, so dp[j] is the cell above and dp[j-1] is the cell to the left.

Think of (i, j) as a cell. Taking the next character of s1 moves you down one row. Taking the next character of s2 moves you right one column. You start at (0, 0) and want to reach (n, m), where n and m are the lengths of s1 and s2. A move is allowed only when the character you take equals s3[i + j].

This matches the unique-paths-on-a-grid pattern, with some cells blocked by character mismatches. The question becomes whether a path of allowed moves leads from the top-left to the bottom-right corner.

Many different move orders land on the same cell. Taking s1 then s2 reaches the same (1, 1) as s2 then s1. Searching without remembering cells redoes that work an exponential number of times. Remember each cell once and the work drops to the number of cells.

Watch the pattern animation

Worked example

Input: s1 = "", s2 = "hello", s3 = "hello"
Output: true
Explanation: With s1 empty, every character of s3 must come from s2 in order. s2 is "hello" and s3 is "hello", so each of the five characters matches and all of s2 is consumed.

Approach 1: Brute force recursion

Try every way to build s3. At state (i, j), look at s3[i + j]. If it equals s1[i], take it and recurse on (i + 1, j). If it equals s2[j], take it and recurse on (i, j + 1).

When both strings are fully used, you have built all of s3, so return true. Check n + m == len(s3) first. With that check passing, using both strings completely means s3 is completely used too.

Steps

  1. Return false if len(s1) + len(s2) != len(s3).
  2. Define go(i, j) where i and j count characters already taken from s1 and s2.
  3. If i == n and j == m, return true.
  4. If i < n and s1[i] == s3[i + j], and go(i + 1, j) is true, return true.
  5. If j < m and s2[j] == s3[i + j], and go(i, j + 1) is true, return true.
  6. Otherwise return false, and call go(0, 0).

Dry run

Trace on s1 = "", s2 = "hello", s3 = "hello". Here n = 0 and m = 5.

  • go(0, 0): i == n, so the s1 branch is skipped. s2[0] = h equals s3[0] = h, so call go(0, 1).
  • go(0, 1): s2[1] = e equals s3[1], so call go(0, 2).
  • go(0, 2), go(0, 3) and go(0, 4) match l, l, o the same way.
  • go(0, 5): i == 0 == n and j == 5 == m, so return true.

True propagates back through all five calls and the answer is true. With one empty string there is no branching. Inputs where both strings match s3[k] split into two calls, and that is where the cost explodes.

Complexity

TimeO(2^(n + m))
SpaceO(n + m)

Let n and m be the lengths of s1 and s2. Each call moves one character forward, so the recursion depth is at most n + m, and that depth is the stack space. Each call makes at most two child calls, so the call tree has at most 2^(n + m) nodes. The same (i, j) is reached by many paths and recomputed each time, which is why this is too slow for n = m = 100.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        n, m = len(s1), len(s2)
        if n + m != len(s3):
            return False

        def go(i: int, j: int) -> bool:
            if i == n and j == m:
                return True
            k = i + j
            if i < n and s1[i] == s3[k] and go(i + 1, j):
                return True
            if j < m and s2[j] == s3[k] and go(i, j + 1):
                return True
            return False

        return go(0, 0)

Approach 2: Memoized recursion

What's slow: the brute force reaches the same (i, j) through many different move orders, and each visit redoes the full search below that cell. There are only (n + 1) * (m + 1) distinct cells, but exponentially many paths into them.

The insight that fixes it: whether you can finish from (i, j) depends only on i and j, not on how you got there. So the first time a cell fails, record it. Any later visit returns false immediately. You only need to store failures, because the first success returns true all the way up the stack.

Steps

  1. Return false if the length check n + m == len(s3) fails.
  2. Create a boolean table failed of size (n + 1) * (m + 1), all false.
  3. Define go(i, j) as in the brute force, but return false at once if failed[i][j] is set.
  4. If i == n and j == m, return true.
  5. Try the s1 move, then the s2 move, each only when the character matches s3[i + j].
  6. If neither move leads to true, set failed[i][j] = true and return false.

Dry run

Trace on s1 = "", s2 = "hello", s3 = "hello". The table failed has 1 row and 6 columns, all false.

  • go(0, 0) calls go(0, 1), which calls go(0, 2), and so on down to go(0, 5).
  • go(0, 5) has i == n and j == m, so it returns true.
  • No cell ever fails, so failed stays all false and each cell is visited once.

The answer is true. On this input the cache never fires. It matters on inputs like s1 = "aa", s2 = "aa", s3 = "aaab", where the cell (1, 1) is reached from both (0, 1) and (1, 0), fails once, and is skipped the second time.

Complexity

TimeO(n * m)
SpaceO(n * m)

Let n and m be the lengths of s1 and s2. A cell (i, j) can only run its two child calls the first time it is entered, because a failure is stored and a success ends the whole search. So at most (n + 1) * (m + 1) cells each do O(1) work, giving O(n * m) time. The failed table holds (n + 1) * (m + 1) booleans, and the recursion adds at most n + m frames, so space is O(n * m).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        n, m = len(s1), len(s2)
        if n + m != len(s3):
            return False

        failed = [[False] * (m + 1) for _ in range(n + 1)]

        def go(i: int, j: int) -> bool:
            if i == n and j == m:
                return True
            if failed[i][j]:
                return False
            k = i + j
            if i < n and s1[i] == s3[k] and go(i + 1, j):
                return True
            if j < m and s2[j] == s3[k] and go(i, j + 1):
                return True
            failed[i][j] = True  # remember the dead end
            return False

        return go(0, 0)
2D Array (Unique Paths on Grid) pattern infographic for Interleaving String

Solution pattern

2D Array (Unique Paths on Grid)

Part of Dynamic Programming (DP) Patterns

Approach 3: Bottom-up DP with one rowOptimal2D Array (Unique Paths on Grid)

What's slow: memoized recursion is already O(n * m) in time, but it stores a full table and pays for recursion frames. A cell only ever depends on the cell above it and the cell to its left.

The insight that fixes it: define dp[i][j] as true when the first i characters of s1 and the first j of s2 can form the first i + j of s3. Then dp[i][j] is true if dp[i-1][j] is true and s1[i-1] == s3[i+j-1], or dp[i][j-1] is true and s2[j-1] == s3[i+j-1]. Fill rows top to bottom, left to right. Row i needs only row i - 1, so one array indexed by j is enough.

When you reach dp[j] in row i, the old value of dp[j] is the cell above. The value at dp[j - 1] was already overwritten in this row, so it is the cell to the left.

Why it is correct. Every valid way to build the first i + j characters of s3 ends with a character taken from s1 or from s2. So dp[i][j] is true exactly when one of those two previous cells is true and its next character matches. Taking the OR of both cases never drops a valid path.

Steps

  1. Return false if n + m != len(s3).
  2. Create dp of length m + 1, all false, and set dp[0] = true for the empty prefixes.
  3. For each i from 0 to n and each j from 0 to m, skip (0, 0).
  4. Let k = i + j - 1, the index in s3 of the character just placed.
  5. Set ok to true if i > 0, dp[j] is true and s1[i-1] == s3[k] (move down from the old value).
  6. Also set ok to true if j > 0, dp[j-1] is true and s2[j-1] == s3[k] (move right from the new value).
  7. Store dp[j] = ok, and after all rows return dp[m].

Dry run

Trace on s1 = "", s2 = "hello", s3 = "hello". Here n = 0, m = 5, and only row i = 0 runs. Start with dp = [T, F, F, F, F, F].

Stepijk = i + j - 1Checkdp after
100noneskip start cell[T, F, F, F, F, F]
2010dp[0] is T and s2[0] = h equals s3[0] = h[T, T, F, F, F, F]
3021dp[1] is T and s2[1] = e equals s3[1] = e[T, T, T, F, F, F]
4032dp[2] is T and s2[2] = l equals s3[2] = l[T, T, T, T, F, F]
5043dp[3] is T and s2[3] = l equals s3[3] = l[T, T, T, T, T, F]
6054dp[4] is T and s2[4] = o equals s3[4] = o[T, T, T, T, T, T]

The loop ends and dp[5] is true, so the answer is true. Because i is 0 in every step, the "move down" check is skipped and only the left neighbour counts.

Complexity

TimeO(n * m)
SpaceO(m)

Let n and m be the lengths of s1 and s2. The two nested loops run (n + 1) * (m + 1) times, and each iteration does a constant number of comparisons, so time is O(n * m). The only extra structure is the array dp of m + 1 booleans, so space is O(m). Choosing s2 as the shorter string makes that O(min(n, m)).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        n, m = len(s1), len(s2)
        if n + m != len(s3):
            return False

        dp = [False] * (m + 1)
        dp[0] = True

        for i in range(n + 1):
            for j in range(m + 1):
                if i == 0 and j == 0:
                    continue
                k = i + j - 1  # index in s3 of the character just placed
                ok = False
                # old dp[j] is the cell above: last char came from s1
                if i > 0 and dp[j] and s1[i - 1] == s3[k]:
                    ok = True
                # dp[j - 1] is already this row: last char came from s2
                if j > 0 and dp[j - 1] and s2[j - 1] == s3[k]:
                    ok = True
                dp[j] = ok

        return dp[m]

Common mistakes

  • Skipping the len(s1) + len(s2) != len(s3) check. Without it the index i + j - 1 can run past the end of s3, or the table can report true for a string of the wrong length. Return false immediately when the lengths differ.
  • Using s3[i - 1] or s3[j - 1] as the target in the DP. A cell (i, j) has placed i + j characters, so the last one is s3[i + j - 1]. Compute k = i + j - 1 once per cell.
  • Greedy matching, such as if s1[i] == s3[k]: take s1. With s1 = "ab", s2 = "ac", s3 = "acab", greedy takes a from s1, then gets stuck on c. The answer is true by taking ac from s2 first, so you must keep both options alive.
  • Initializing the first row or column to true without checking characters. dp[0][j] must require that s2[0..j-1] equals s3[0..j-1]. In the loop version above this happens naturally because every cell goes through the same two checks.
  • Filling the 1D array from right to left. Then dp[j - 1] still holds the previous row, and the move from the left reads stale data. Iterate j upward so dp[j - 1] is already this row's value.
  • Overwriting dp[0] wrongly in later rows. In row i > 0, dp[0] must become dp[0] and s1[i-1] == s3[i-1]. The unified loop does this, because for j = 0 only the s1 check can fire.

Edge cases

  • s1 = "", s2 = "", s3 = "": both strings are empty and s3 is empty, so the answer is true. The start cell is the goal cell.
  • s1 = "", s2 = "hello", s3 = "hello": only one source is available, so the answer is true. With s3 = "hellp" it is false.
  • Length mismatch such as s1 = "a", s2 = "b", s3 = "abc": return false before touching the table.
  • s1 = "ab", s2 = "ba", s3 = "bbaa": the letter counts match but no valid order exists, so the answer is false. Counting letters alone is not enough.
  • s1 = "aa", s2 = "aa", s3 = "aaaa": every cell matches and many paths reach the same cell. The answer is true, and this is the shape that blows up the brute force.
  • Both strings 100 characters of a and s3 is 199 a followed by b: this is the adversarial case for unmemoized recursion. The answer is false, and the DP handles it in about 10,000 cell updates.

Follow-ups interviewers ask

Can you reduce the extra space below O(n * m)?
Yes, and the third approach already does. Row i only reads row i - 1 and the cell to its left, so one array of length m + 1 is enough. If you want the smaller array, swap the strings so that s2 is the shorter one. That gives O(min(n, m)) space with the same O(n * m) time.
How would you return an actual interleaving instead of true or false?
Keep the full (n + 1) by (m + 1) table, since the one-row version overwrites the history you need. Start at the goal cell (n, m) and walk back. At (i, j), if dp[i-1][j] is true and s1[i-1] equals s3[i+j-1], the last character came from s1 and you step up. Otherwise step left and use s2. Reverse the recorded choices at the end.
How does this change with three source strings?
The state becomes (i, j, l), the counts taken from each string, and the target index is i + j + l. The table grows to (n + 1) * (m + 1) * (p + 1) cells, each with up to three transitions. Time and space are O(n * m * p). With k strings the state space grows as the product of all lengths, so it does not scale to large k.

Interleaving String FAQ

What is the time complexity of Interleaving String?

The DP solution runs in O(n * m) time, where n and m are the lengths of s1 and s2. It fills (n + 1) * (m + 1) cells with constant work each. Plain recursion without caching is O(2^(n + m)). The 1D version uses O(m) space.

Why use dynamic programming for Interleaving String?

Whether the rest of s3 can be built depends only on how many characters you took from s1 and from s2, which is the pair (i, j). Many move orders reach the same pair, so the same subproblem repeats exponentially often. DP computes each of the (n + 1) * (m + 1) pairs once. A greedy choice cannot work, because when both strings match the current character you cannot know which one to take.

Why does the check len(s1) + len(s2) == len(s3) come first?

Every character of both strings must be used exactly once, so any valid s3 has exactly that length. If the lengths differ, the answer is false with no further work. The check also guarantees that the index i + j - 1 never leaves s3 inside the DP.

Can Interleaving String be solved in O(1) extra space?

No known approach does it in general. The answer depends on many (i, j) states, and you must remember which ones are reachable. The best practical bound is O(min(n, m)) extra space with the one-row DP, since you only need the previous row.

Is there a bit manipulation solution for Interleaving String?

One exists in principle: each of the n + m positions of s3 is assigned to s1 or s2, which is a bitmask with exactly n ones. Checking all such masks is the brute force in disguise and takes exponential time. The DP over (i, j) is the efficient version of the same idea.

Can I write Interleaving String in Python or Java with the same approach?

Yes, the DP is identical in every language. The loops, the index k = i + j - 1 and the two checks do not change. In Java, C# and Go, index strings by position and watch that i - 1 and j - 1 are used only when i and j are positive.

Asked at

See which companies ask this — Pro

Practise it