Quick Overview

Given two lowercase strings a and b, find the smallest number of times a must be repeated so that b appears inside the result as a substring, or return -1 when no count works. It tests reasoning about string periodicity, bounding the search, and the cost of substring matching.

Minimum number of times to repeat a string so another string becomes a substring

Company: Google

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

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 not possible for `b` to be a substring of the repeated `a`, return `-1`. Repeating `"abc"` 0 times gives `""`, 1 time gives `"abc"`, and 2 times gives `"abcabc"`. ### Function Signature ```python def repeated_string_match(a: str, b: str) -> int: ``` ### Rules - A substring is a contiguous run of characters. - Return the smallest count `k` such that `b` occurs in `a` repeated `k` times. Return `-1` when no count works. ### Constraints - `1 <= len(a), len(b) <= 10^4` - `a` and `b` consist of lowercase English letters. ### Examples ```text Input: a = "abcd", b = "cdabcdab" Output: 3 ``` Two copies give `"abcdabcd"`, which is as long as `b` but is not equal to it. Three copies give `"abcdabcdabcd"`, and `b` starts at index 2. ```text Input: a = "a", b = "aa" Output: 2 ``` One copy is shorter than `b`. Two copies give `"aa"`, which is `b` itself. ```text Input: a = "abc", b = "acb" Output: -1 ``` In any repetition of `"abc"`, the letter after `a` is always `b`, so `"ac"` never appears and `b` cannot either.

Overview: Given two lowercase strings a and b, find the smallest number of times a must be repeated so that b appears inside the result as a substring, or return -1 when no count works. It tests reasoning about string periodicity, bounding the search, and the cost of substring matching.

You are given two strings `a` and `b`. Repeating `a` k times means writing k copies of `a` back to back. For example, repeating `"abc"` 0 times gives `""`, 1 time gives `"abc"`, and 2 times gives `"abcabc"`. Return the smallest count `k` such that `b` is a substring of `a` repeated `k` times, where a substring is a contiguous run of characters. If no count works, return `-1`. Implement `repeated_string_match(a, b)`, which returns that count as an integer. Because `b` is never empty, a valid count is always at least 1, and every answer fits in a 32-bit signed integer. Example 1: ```text Input: a = "abcd", b = "cdabcdab" Output: 3 ``` Two copies give `"abcdabcd"`, which is as long as `b` but is not equal to it. Three copies give `"abcdabcdabcd"`, and `b` starts at index 2. Example 2: ```text Input: a = "abc", b = "acb" Output: -1 ``` In any repetition of `"abc"`, the letter after every `"a"` is `"b"`, so `"ac"` never appears and `b` cannot either. Constraints: - `1 <= len(a), len(b) <= 10^4` - `a` and `b` consist of lowercase English letters.

Constraints

  • 1 <= len(a), len(b) <= 10^4
  • a and b consist of lowercase English letters.

Examples

Input: ('a', 'a')

Expected Output: 1

Explanation: Minimum valid input: one copy of a already equals b.

Input: ('a', 'b')

Expected Output: -1

Explanation: Minimum valid input with no match: b holds a letter that a lacks.

Hints

  1. Before b can fit inside the repeated string, the repeated string must be at least as long as b. What is the fewest copies that reaches that length?
  2. The repeated string looks the same after shifting by one whole copy of a. Where inside the first copy could an occurrence of b start, and how many copies would it need from there?
  3. Check whether adding copies past a certain point can ever create a new place for b to start.

Community answers

Answer by nitkumthot

import math def repeated_string_match(a: str, b: str) -> int: min_k = math.ceil(len(b) / len(a)) repeated_a = a * (min_k + 1) # Find the earliest index where b appears inside repeated_a start_idx = rabin_karp(repeated_a, b) if start_idx == -1: return -1 # Check if the match finishes within min_k copies of a if start_idx + len(b) <= len(a) * min_k: return min_k return min_k + 1 def rabin_karp(text: str, pattern: str) -> int: n, m = len(text), len(pattern) if m > n: return -1 BASE = 31 MOD = 10**9 + 7 # Precompute BASE^(m - 1) % MOD (the place value of the leftmost character) highest_pow = pow(BASE, m - 1, MOD) pattern_hash = 0 window_hash = 0 # Step 1: Compute initial hashes for pattern and the first window of text for i in range(m): p_val = ord(pattern[i]) - ord('a') + 1 t_val = ord(text[i]) - ord('a') + 1 pattern_hash = (pattern_hash * BASE + p_val) % MOD window_hash = (window_hash * BASE + t_val) % MOD # Step 2: Slide the window across text one character at a time for i in range(n - m + 1): # Compare hashes first; only verify characters if hashes match if window_hash == pattern_hash and text[i : i + m] == pattern: return i # Roll the hash forward to the next window if we aren't at the end if i + m < n: out_val = ord(text[i]) - ord('a') + 1 in_val = ord(text[i + m]) - ord('a') + 1 window_hash = ((window_hash - out_val highest_pow) BASE + in_val) % MOD return -1

Answer by devinliao046

def repeated_string_match(a: str, b: str) -> int: n, m = len(a), len(b) for i in range(n): if a[i] == b[0]: if all(a[(i+j) % n] == b[j] for j in range(m)): return (i + m + n - 1) // n return -1

Answer by akkida746

static int solve(String a, String b) { int min = Integer.MAX_VALUE; StringBuilder sb = new StringBuilder(); int maxRepeat = 2 + (b.length() + a.length() - 1) / a.length(); int repeatCount = 0; while(maxRepeat-- > 0) { repeatCount++; sb.append(a); if(sb.toString().contains(b)) { return repeatCount; } } return -1; } urn -1;

Answer by nicolasjack1994

k = (len(b) + len(a) - 1) // len(a) repeated = a * k if b in repeated: return k if b in repeated + a: return k + 1 return -1

Answer by hvp4

def repeated_string_match(a: str, b: str) -> int: if not b: return 0 if not a: return -1 count = 0 while count * len(a) < len(b): count += 1 repeated = a * count if b in repeated: return count if b in repeated + a: return count + 1 return -1

Fewest Repetitions of a String to Contain Another

mediumGoogleSoftware Engineer

You are given two strings a and b. Repeating a k times means writing k copies of a back to back. For example, repeating "abc" 0 times gives "", 1 time gives "abc", and 2 times gives "abcabc".

Return the smallest count k such that b is a substring of a repeated k times, where a substring is a contiguous run of characters. If no count works, return -1.

Implement repeated_string_match(a, b), which returns that count as an integer. Because b is never empty, a valid count is always at least 1, and every answer fits in a 32-bit signed integer.

Example 1:

Input: a = "abcd", b = "cdabcdab"
Output: 3

Two copies give "abcdabcd", which is as long as b but is not equal to it. Three copies give "abcdabcdabcd", and b starts at index 2.

Example 2:

Input: a = "abc", b = "acb"
Output: -1

In any repetition of "abc", the letter after every "a" is "b", so "ac" never appears and b cannot either.

Constraints:

  • 1 <= len(a), len(b) <= 10^4
  • a and b consist of lowercase English letters.

Examples

Example 1
Input
('a', 'a')
Output
1
Notes
Minimum valid input: one copy of a already equals b.
Example 2
Input
('a', 'b')
Output
-1
Notes
Minimum valid input with no match: b holds a letter that a lacks.

Constraints

  • •1 <= len(a), len(b) <= 10^4
  • •a and b consist of lowercase English letters.

Comments (7)

Submit your answer

Approved first answer today earns 30 XP
Bold⌘BItalic⌘IInline code⌘`Bullet listTab to nest (○ ■)Numbered listTab to nest (a. i.)QuoteCode block
Formatting help
Signature
def repeated_string_match(a: str, b: str) -> int:
Sample call
repeated_string_match('a', 'a')
Language
Case 1
Input
('a', 'a')
Expected
1
Case 2
Input
('a', 'b')
Expected
-1

Browse More Questions

Show the approach

Approach

Let n = len(a), m = len(b) and q = ceil(m / n). A repetition with fewer than q copies is shorter than b, so no smaller count can work. The repetition of a is periodic with period n: if b starts at index p in some repetition, it also starts at index p mod n, inside the first copy, of any repetition long enough to hold it. From a start below n, b ends at an index of at most n - 1 + m - 1, so ceil((n - 1 + m) / n) <= q + 1 copies always hold it. So b occurs in some repetition exactly when it occurs in t = a repeated q + 1 times.

The solution builds t (shorter than m + 2n) and scans it with the Knuth-Morris-Pratt matcher. The failure table stores, for every prefix of b, the length of its longest proper prefix that is also a suffix. During the scan, j is always the length of the longest prefix of b that ends at the current index of t. The first index i where j reaches m is the earliest end of any occurrence. Covering indices 0 through i takes ceil((i + 1) / n) = i // n + 1 copies, and an occurrence that ends later can never need fewer copies, so the function returns i // n + 1. If the scan ends with no full match, no repetition contains b and the function returns -1.

Edge cases: b shorter than a still needs two copies when it wraps across the copy boundary (a = "abcdef", b = "efab" gives 2). When b is a repeated exactly q times the answer is q. A letter of b missing from a, or a pair of neighboring letters that never occurs in the repetition, gives -1. The matcher does a bounded amount of work per character overall, so long runs of one letter cannot make the scan quadratic.

Time complexity:
O(len(a) + len(b))
Space complexity:
O(len(a) + len(b))