All problems
0465MediumStringString MatchingZ AlgorithmKnuth–Morris–Pratt AlgorithmBoyer–Moore String-Search Algorithm

Repeats Of A Motif Holding A Stretch

Tracked in this browser only
Write code

Trains the technique from

LeetCode 686Repeated String Match

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

A loom weaves a band by repeating the pattern motif end to end, so weaving it three times gives a band reading motif then motif then motif with nothing between them. Each letter stands for one pick of the shuttle.

A buyer wants the band to contain stretch as an unbroken run of picks somewhere along it, anywhere at all - the run need not start where a copy of the motif starts.

Return the smallest number of whole repeats of motif that produces a band containing stretch. Return -1 if no number of repeats ever does. Only whole repeats count: the loom cannot stop part way through the motif, though the wanted run may finish before the band does.

Examples

Example 1

Input
motif = "ptr", stretch = "rptrp"
Output
3

Weaving the motif three times gives ptrptrptr, and the wanted run sits in it starting at the third pick.

Example 2

Input
motif = "gh", stretch = "hg"
Output
2

One repeat reads gh, which does not hold hg, while two repeats read ghgh and hold it across the join.

Example 3

Input
motif = "mno", stretch = "nomx"
Output
-1

Every band woven from mno is made only of m, n and o picks, so a run containing x can never appear.

Constraints

  • 1 <= motif.length <= 10^4
  • 1 <= stretch.length <= 10^4
  • motif and stretch consist of lowercase English letters.

The signature

The editor is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

Python
def motif_repeats(motif: str, stretch: str) -> int:
Java
public int motifRepeats(String motif, String stretch)
September 7
Apply