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 the repeated a
, return -1
.
a
for a certain number of times contains b
as a substring.a
and b
?
a
or b
be empty?
a
is empty and b
is not, it’s impossible to form b
. If b
is empty, 0
repeats would be a valid return value since an empty string is trivially a substring of any string.n
of a
such that it could potentially contain b
. This can be approximated by the ceiling of the length of b
divided by the length of a
.n
repetitions of a
and check if b
is a substring. If not, incrementally add another repetition and check again.n + 2
repetitions. This is because increasing repetitions beyond this point without finding b
will not suddenly make b
fit.b
is found within these checks, return the number of repetitions. If not, return -1
.def repeatedStringMatch(a: str, b: str) -> int:
import math
# Get the minimum number of repetitions needed
min_reps = math.ceil(len(b) / len(a))
# Check if b is a substring in the possible range of repetitions
for i in range(min_reps, min_reps + 3):
if b in a * i:
return i
return -1
Checking if b
is a substring of the repeated a
involves a check that can run in O(m * n)
time in the worst case, where m
is the length of b
and n
is the length of a
. However, generally, this will be much faster due to the nature of substring checking and early exits.
The loop runs at most 3 times, making the overall time complexity about O(3 * m * n)
, which simplifies to O(m * n)
.
(min_reps + 2) * len(a)
. In the worst case, this can be space linear in the length of the repeated string. Thus, the space complexity is O((min_reps + 2) * n)
.This approach ensures both efficiency and clarity in checking for the substring b
within the repeated a
.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?