Repeated String Match II Problem
Description
LeetCode Problem 4105.
You are given two strings a and b consisting of lowercase English letters, and two integers x and y.
Return true if the string formed by repeating b exactly y times (b * y) is a substring of the string formed by repeating a exactly x times (a * x). Otherwise, return false.
Example 1:
Input: a = "ab", b = "abab", x = 2, y = 1
Output: true
Explanation:
- a * x = "ab" * 2 = "abab"
- b * y = "abab" * 1 = "abab"
- They are identical, so b * y is a substring of a * x. Thus, the answer is true.
Example 2:
Input: a = "abc", b = "bc", x = 2, y = 3
Output: false
Explanation:
- a * x = "abc" * 2 = "abcabc"
- b * y = "bc" * 3 = "bcbcbc"
- The answer is false as b * y = "bcbcbc" is not a substring of a * x = "abcabc".
Example 3:
Input: a = "abcd", b = "cdab", x = 2, y = 1
Output: true
Explanation:
- a * x = "abcd" * 2 = "abcdabcd"
- b * y = "cdab" appears in a * x = "abcdabcd" at indices [2..5]. Thus, the answer is true.
Constraints:
1 <= a.length <= 1001 <= b.length <= 1001 <= x <= 10^91 <= y <= 10^9aandbconsist of lowercase English letters.
Solution
Approach: Reduce to Primitive Roots
The repetition counts are huge, but the strings are periodic, so we can reason about them instead of building them. Let ra and rb be the primitive roots of a and b, the shortest strings that repeat to give a and b. Then a * x is ra repeated, and b * y is rb repeated. Let lenA = |a| * x and lenB = |b| * y. If lenB > lenA, the answer is false.
- Short
b * y(lenB < |ra| + |rb|, at most about 200 letters): build it directly. A match can be shifted to start within the first|ra|letters ofa * x, so it is enough to search a copy ofrarepeated aboutlenB / |ra| + 2times (orxtimes, if that is fewer). - Long
b * y: it has both period|ra|and period|rb|, so by the Fine and Wilf theorem it has periodgcd(|ra|, |rb|). Sincerbis primitive, this forces|ra| = |rb|andrbmust be a rotation ofra. Find the smallest offsetoffwith(ra + ra).find(rb). The first match ina * xstarts atoff, so the answer istrueexactly whenoff + lenB <= lenA.
Complexity: O(|a| * |b|) time in the worst case for finding roots and searching, and O(|a| + |b|) space.
class Solution:
def repeatedStringMatch(self, a: str, b: str, x: int, y: int) -> bool:
def root(s: str) -> str:
# the shortest string that repeats to give s
for d in range(1, len(s) + 1):
if len(s) % d == 0 and s[:d] * (len(s) // d) == s:
return s[:d]
ra, rb = root(a), root(b)
len_a = len(a) * x
len_b = len(b) * y
if len_b > len_a:
return False
if len_b < len(ra) + len(rb):
# short enough to build: a match can start within the first len(ra) letters
reps = min(len_a // len(ra), len_b // len(ra) + 2)
return rb * (len_b // len(rb)) in ra * reps
# long: both strings are periodic, so they must share one period (Fine and Wilf)
if len(ra) != len(rb):
return False
off = (ra + ra).find(rb) # smallest rotation of ra that equals rb
return off >= 0 and off + len_b <= len_a