Repeated String Match (LeetCode 686): Solution and Explanation
Repeat a some number of times and find the fewest repetitions that contain b as a substring, or return -1 if no number of repetitions works.
Intuition
The repeated string has to be at least as long as b, so you need at least q = ceil(len(b) / len(a)) copies. Anything shorter cannot hold b.
The repeated string is periodic: it looks the same after shifting by len(a). If b occurs anywhere, it also occurs with its start inside the first copy, at some index between 0 and len(a) - 1.
A start inside the first copy plus len(b) characters reaches at most len(a) - 1 + len(b) characters, which always fits in q + 1 copies. So if b is not inside q + 1 copies, it is not inside any number of copies.
That leaves exactly two candidates to test, q and q + 1. Building the string and running a substring search on each gives the answer.
Approach: Test q and q + 1 copies
- Start with
built = aandcount = 1. - While
builtis shorter thanb, appendaand increasecount. Nowcount = q. - If
bis a substring ofbuilt, returncount. - Append one more
a. Ifbis a substring now, returncount + 1. - Otherwise return -1.
Step-by-step example
a = "abcd", b = "cdabcdab"
- len(b) = 8 and len(a) = 4, so start with one copy and append until the length reaches 8:
built = "abcdabcd", count = 2. - Search for b. Start 0 fails at the first character (a vs c), start 1 fails too (b vs c).
- Start 2 matches "cdab" and then needs 4 more characters, but only 2 are left. Two copies cannot hold b.
- Append a spare copy:
built = "abcdabcdabcd", count = 3. - Start 2 now matches all 8 characters, so return 3.
Code: Python, Java, C++
1class Solution:
2 def repeatedStringMatch(self, a: str, b: str) -> int:
3 count = 1
4 built = a
5 while len(built) < len(b):
6 built += a
7 count += 1
8 if b in built:
9 return count
10 built += a
11 if b in built:
12 return count + 1
13 return -11class Solution {
2 public int repeatedStringMatch(String a, String b) {
3 int count = 1;
4 StringBuilder built = new StringBuilder(a);
5 while (built.length() < b.length()) {
6 built.append(a);
7 count++;
8 }
9 if (built.indexOf(b) >= 0) {
10 return count;
11 }
12 built.append(a);
13 if (built.indexOf(b) >= 0) {
14 return count + 1;
15 }
16 return -1;
17 }
18}1class Solution {
2public:
3 int repeatedStringMatch(string a, string b) {
4 int count = 1;
5 string built = a;
6 while (built.size() < b.size()) {
7 built += a;
8 count++;
9 }
10 if (built.find(b) != string::npos) {
11 return count;
12 }
13 built += a;
14 if (built.find(b) != string::npos) {
15 return count + 1;
16 }
17 return -1;
18 }
19};Time and space complexity
O(n * (n + m))
The built string has at most m + 2n characters, where n = len(a) and m = len(b). A naive substring search tries each start and compares up to m characters; only the first n starts can be the first match. With KMP or a library search tuned for this, it is close to O(n + m).
O(n + m)
The built string holds q + 1 copies of a, which is at most m + 2n characters.
Other approaches
Keep appending until a limit (time O((m / n) * (n + m) * m), space O(n + m))
Append a and test after every append until the length passes len(b) + len(a). It returns the same answer but runs a substring search after each copy, which wastes work.
Modular comparison without building (time O(n * m), space O(1))
For each start k in the first copy, compare b[j] with a[(k + j) % n]. If all match, the answer is ceil((k + m) / n). This uses no extra string at all.
KMP or Rabin-Karp on the repeated text (time O(n + m), space O(m))
Run a linear-time matcher for b over q + 1 copies of a, read through modular indexing. It guarantees linear time on adversarial inputs like long runs of one letter.
Common mistakes
- Stopping at q copies. In Example 1, b starts at index 2, so it spills into a third copy even though two copies are already long enough.
- Looping forever when b is impossible. More than q + 1 copies never adds a new start position, so stop there and return -1.
- Forgetting that b may be shorter than a. With a = "abc" and b = "cab", one copy is long enough but the answer is 2.
Frequently asked questions
Why is q + 1 copies always enough?
Any match can be shifted left by whole copies of a until it starts at some index k < len(a). The match then ends before k + len(b) <= len(a) - 1 + len(b), and q + 1 copies have at least len(b) + len(a) characters.
Why does the answer start at ceil(len(b) / len(a))?
A substring cannot be longer than the string that contains it, so the repeated string needs at least len(b) characters.
Can the answer be 1 when b is longer than a?
No. One copy has len(a) characters, which is shorter than b, so the build loop always adds copies first.
Is the library substring search fast enough?
Yes for these limits. The built string is at most about 3 * 10^4 characters, and library searches handle that quickly. KMP removes the worst case if you want a guarantee.