- categories: Code, Interview Question, leetcode, Medium
- source: https://leetcode.com/problems/interleaving-string
- topics: Dynamic Programming
Description
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 + ... + snt = t1 + t2 + ... + tm|n - m| <= 1- The interleaving is
s1 + t1 + s2 + t2 + s3 + t3 + ...ort1 + s1 + t2 + s2 + t3 + s3 + ...
Note: a + b is the concatenation of strings a and b.
Idea
- Top-Down Recursion with memorization using 2 indices
Code
class Solution:
def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
@cache
def dp(t, i, j):
if t == 1:
return i == 1 and s1[0] == s3[0] or j == 1 and s2[0] == s3[0]
return (
i > 0 and s3[t-1] == s1[i-1] and dp(t-1, i-1, j) or
j > 0 and s3[t-1] == s2[j-1] and dp(t-1, i, j-1)
)
if len(s1) + len(s2) != len(s3):
return False
if len(s1) == len(s2) == len(s3) == 0:
return True
return dp(len(s3), len(s1), len(s2))