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

मी 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.