> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Repeated String Match Python Solution

> Tested Python solution for LeetCode 686 with 24 pytest cases. Generate a practice environment with lcpy.

LeetCode 686, [Medium](/catalog/medium). Topics: [String](/catalog/topics/string), [String Matching](/catalog/topics/string-matching), Z Algorithm, Knuth-Morris-Pratt Algorithm, Boyer-Moore String-Search Algorithm. [View on LeetCode](https://leetcode.com/problems/repeated-string-match/description/).

Generate this problem as a practice environment: tested reference solution, 24 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 686   # by problem number
lcpy gen -s repeated_string_match   # by problem name
```

## 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`.

**Notice:** string `"abc"` repeated 0 times is `""`, repeated 1 time is `"abc"` and repeated 2 times is `"abcabc"`.

### Examples

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

```
Input: a = "a", b = "aa"
Output: 2
```

### Constraints

* 1 \<= a.length, b.length \<= 10^4
* a and b consist of lowercase English letters.

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/repeated_string_match/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/repeated_string_match/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(len(a) + len(b))
    # Space: O(len(a) + len(b))
    def repeated_string_match(self, a: str, b: str) -> int:
        min_repeats = -(-len(b) // len(a)) if b else 1
        for k in (min_repeats, min_repeats + 1):
            if b in a * k:
                return k
        return -1
```

## Complexity

| Time | Space |
| - | - |
| O(len(a) + len(b)) | O(len(a) + len(b)) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.