Interleaving String — LeetCode 97 Python Solution

MediumStringDynamic Programming
Problem
#97
Reading time
3 min

The problem

Given strings s1, s2, and s3, find whether s3 is formed by an interleaving of s1 and s2. An interleaving of two strings s and t is a configuration where s and t are divided into n and m substrings respectively, such that: s = s1 + s2 + ...

Example

Input
s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output
true
Explanation
One way to obtain s3 is:

Python solution

Python
class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        @cache
        def dfs(i: int, j: int) -> bool:
            if i >= m and j >= n:
                return True
            k = i + j
            if i < m and s1[i] == s3[k] and dfs(i + 1, j):
                return True
            if j < n and s2[j] == s3[k] and dfs(i, j + 1):
                return True
            return False

        m, n = len(s1), len(s2)
        if m + n != len(s3):
            return False
        return dfs(0, 0)

Complexity

MeasureComplexity
TimeO(m \times n)
SpaceO(m \times n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 97. Interleaving String is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

On study lists

This problem is on NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 97. Interleaving String?
LeetCode 97. Interleaving String is rated Medium on LeetCode.
What is the time complexity of LeetCode 97. Interleaving String?
The Python solution on this page runs in O(m \times n).
What is the space complexity of LeetCode 97. Interleaving String?
The Python solution on this page uses O(m \times n) auxiliary space.
What topics does LeetCode 97. Interleaving String cover?
LeetCode 97. Interleaving String is tagged String and Dynamic Programming on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview