← DSA
MEDIUM

Interleaving String

PracticeNeetCode ↗LeetCode ↗

Given strings s1, s2, and s3, determine whether s3 can be formed by interleaving the characters of s1 and s2 while preserving the relative order of characters within each source string.

Example

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

Key Pointers

Step-by-Step Analysis

  1. If the lengths don't add up, return False immediately.
  2. Build a boolean grid sized (len(s1)+1) × (len(s2)+1), with dp[0][0] = True (two empty strings trivially interleave to an empty result).
  3. For each cell (i, j): it's True if s1[i-1] matches the corresponding s3 character and dp[i-1][j] is True, or if s2[j-1] matches and dp[i][j-1] is True.
  4. The bottom-right cell, dp[len(s1)][len(s2)], holds the final answer.

Complexity

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

Code

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

    dp = [[False] * (n + 1) for _ in range(m + 1)]
    dp[0][0] = True

    for i in range(m + 1):
        for j in range(n + 1):
            if i > 0 and s1[i - 1] == s3[i + j - 1] and dp[i - 1][j]:
                dp[i][j] = True
            if j > 0 and s2[j - 1] == s3[i + j - 1] and dp[i][j - 1]:
                dp[i][j] = True

    return dp[m][n]

Code Explanation

How the solution above works, piece by piece.

  1. If the lengths don't add up, it's impossible.
  2. dp[i][j] = can s1[:i] and s2[:j] interleave to form s3[:i+j]? dp[0][0] = True.
  3. Coming from above: the last character came from s1, so s1[i-1] must equal s3[i+j-1] and dp[i-1][j] must be true.
  4. Coming from the left: same check with s2[j-1] and dp[i][j-1].
  5. dp[m][n] is the answer. O(m × n) time and space.

Visual Walkthrough

Running it on s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac":

Interleaving DP table·dbbca·TFFFFFaTFFFFFaTTTTTFbFTTFTFcFFTTTTcFFFTFTdp[i][j]: can the first i of s1 andfirst j of s2 form the first i + j of s3?step down = take a letter from s1step right = take a letter from s2bottom-right T → true
A True cell means the two prefixes can be woven into the matching prefix of s3. A path of True cells from the top-left to the bottom-right (moving only down or right) is one valid interleaving.
Trueanswer

Video Explanation

NeetCode — Dynamic Programming, LeetCode 97