Repeated String Match — LeetCode 686 Python Solution

MediumStringString Matching
Problem
#686
Pattern
Hash Map
Reading time
2 min

The problem

Given two strings a and b, return the minimum number of times you should repeat string a so that string b is a substring of it. If it is impossible for b​​​​​​ to be a substring of a after repeating it, return -1.

Example

Input
a = "abcd", b = "cdabcdab"
Output
3
Explanation
We return 3 because by repeating a three times "abcdabcdabcd", b is a substring of it.

Python solution

Python
class Solution:
    def repeatedStringMatch(self, a: str, b: str) -> int:
        m, n = len(a), len(b)
        ans = ceil(n / m)
        t = [a] * ans
        for _ in range(3):
            if b in ''.join(t):
                return ans
            ans += 1
            t.append(a)
        return -1

Complexity

MeasureComplexity
TimeO(n)
SpaceO(1) to O(n) auxiliary

Pattern: Hash Map

Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 686. Repeated String Match is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 686. Repeated String Match?
LeetCode 686. Repeated String Match is rated Medium on LeetCode.
What topics does LeetCode 686. Repeated String Match cover?
LeetCode 686. Repeated String Match is tagged String and String Matching 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