Tensorum
YouTubeশেখা শুরু করুন
LeetCode 97 · String DP / Word Break

Interleaving String

LeetCode 97 · মাঝারি · সমাধান, intuition ও ধাপে ধাপে ওয়াকথ্রু

State (i, j) — k is always i + j, so only two indices matter.

মাঝারিStringDynamic Programming
LeetCode-এ খুলুন ↗

আমি Interleaving String (LeetCode 97) এভাবে সমাধান করেছি — String DP / Word Break প্যাটার্নের একটি মাঝারি প্রবলেম। নিচে: intuition, ধাপে ধাপে approach, আমার accepted Python কোড, animated test cases আর line-by-line debugger।

নিচের বিবরণ ইংরেজিতে।

Intuition

Walk s3 one character at a time. The next character must come from the front of what's left of s1 or of s2. If it matches one, advance that string; if it matches both, try both. Memoising on the two positions removes the exponential branching.

Approach

  1. 1

    Lengths must add up, otherwise it's impossible.

  2. 2

    If s1 is used up, the rest of s2 must equal the rest of s3 (and vice versa).

  3. 3

    If s1[i] == s3[k], try advancing s1; if s2[j] == s3[k], try advancing s2.

  4. 4

    Return True if either branch succeeds; lru_cache stores each (i, j, k).

আমি কীভাবে সমাধান করেছি

Recursion + memoPythonO(m·n) time · O(m·n) space
from functools import lru_cache
class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        if len(s1)+len(s2)!=len(s3):
            return False
        @lru_cache(maxsize=None)
        def dfs(i,j,k):
            if i==len(s1):
                return s2[j:]==s3[k:]
            if j==len(s2):
                return s1[i:]==s3[k:]
            case1=False
            case2=False
            if s1[i]==s3[k]:
                case1 = dfs(i+1,j,k+1)
            if s2[j]==s3[k]:
                case2 = dfs(i,j+1,k+1)
            return case1 or case2

        return dfs(0,0,0)
স্টেপ-থ্রু লোড হচ্ছে…

Interleaving String — সাধারণ প্রশ্ন

Interleaving String-এর পেছনে intuition কী?

Walk s3 one character at a time. The next character must come from the front of what's left of s1 or of s2. If it matches one, advance that string; if it matches both, try both. Memoising on the two positions removes the exponential branching.

Interleaving String (LeetCode 97) কীভাবে সমাধান করবেন?

1. Lengths must add up, otherwise it's impossible. 2. If s1 is used up, the rest of s2 must equal the rest of s3 (and vice versa). 3. If s1[i] == s3[k], try advancing s1; if s2[j] == s3[k], try advancing s2. 4. Return True if either branch succeeds; lru_cache stores each (i, j, k).

Interleaving String-এর time আর space complexity কত?

Time: O(m · n)। Space: O(m · n)। (Accepted approach: Recursion + memo।)

Interleaving String-এ সাধারণ ভুলগুলো কী?

Greedy 'take from s1 when it matches' fails when both strings share a character. Check the length sum first — it prunes many inputs instantly.