Repeated String Match — LeetCode 686 Python Solution
- Problem
- #686
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
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
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 -1Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.