Tensorum
YouTubeसीखना शुरू करें
LeetCode 686 · String Matching (KMP / Rabin-Karp)

Repeated String Match

LeetCode 686 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Only ceil(|B|/|A|) or one more repeat can work.

मध्यमStringString MatchingZ AlgorithmKnuth–Morris–Pratt AlgorithmBoyer–Moore String-Search Algorithm

मैंने Repeated String Match (LeetCode 686) ऐसे हल किया — String Matching (KMP / Rabin-Karp) पैटर्न का एक मध्यम प्रॉब्लम। नीचे: intuition, कदम-दर-कदम approach, मेरा accepted Python कोड, animated test cases और line-by-line debugger।

नीचे का विवरण अंग्रेज़ी में है।

Intuition

B can only fit inside A repeated enough times to be at least as long as B — or one more copy, in case B starts partway through A. So try those two counts and check for B with a rolling-hash (Rabin–Karp) search.

Approach

  1. 1

    count = ceil(len(b) / len(a)); str = a repeated count times.

  2. 2

    If b is found in str, return count.

  3. 3

    Else try one more copy; otherwise -1.

  4. 4

    Rabin–Karp: compare a rolling character-sum hash, and verify characters on a hash hit.

मैंने कैसे हल किया

Repeat + Rabin–KarpPythonO(n+m) expected
import math


class Solution:
    def repeatedStringMatch(self, a, b):
        count = math.ceil(len(b) / len(a))
        s = a * count
        if self.rabinKarp(s, b):
            return count
        elif self.rabinKarp(s + a, b):
            return count + 1
        else:
            return -1

    def rabinKarp(self, b, a):
        if len(a) > len(b):
            return False
        m = len(a)
        n = len(b)
        aHash = 0
        bHash = 0
        for i in range(m):
            aHash += ord(a[i])
            bHash += ord(b[i])
        for i in range(n - m + 1):
            if aHash == bHash:
                j = 0
                while j < m:
                    if a[j] != b[i + j]:
                        break
                    j += 1
                if j == m:
                    return True
            if i < n - m:
                bHash = bHash - ord(b[i]) + ord(b[i + m])
        return False
स्टेप-थ्रू लोड हो रहा है…

Repeated String Match — अक्सर पूछे जाने वाले प्रश्न

Repeated String Match के पीछे intuition क्या है?

B can only fit inside A repeated enough times to be at least as long as B — or one more copy, in case B starts partway through A. So try those two counts and check for B with a rolling-hash (Rabin–Karp) search.

Repeated String Match (LeetCode 686) कैसे हल करें?

1. count = ceil(len(b) / len(a)); str = a repeated count times. 2. If b is found in str, return count. 3. Else try one more copy; otherwise -1. 4. Rabin–Karp: compare a rolling character-sum hash, and verify characters on a hash hit.

Repeated String Match की time और space complexity क्या है?

Time: O(n + m) expected। Space: O(n)। (Accepted approach: Repeat + Rabin–Karp।)

Repeated String Match में आम गलतियाँ क्या हैं?

The additive hash collides often — the character check after a hash match is essential.