#686

Repeated String Match

Medium Repeat + KMP search

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

Return the fewest times you must repeat string a so that b becomes a substring of the result, or -1 if it's impossible.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: the fewest copies of a so that b fits inside.

Why this works: you need at least enough copies to be as long as b; one extra copy covers b starting in the middle of a copy.

Example: a = "abcd", b = "cdabcdab"

2 copies "abcdabcd" — not inside3 copies "abcdabcdabcd" — contains b → 3

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Stopping at ceil(|b| / |a|) copies — b may start in the middle of a copy and need one extra.

Solve on LeetCode ↗
Complexity
  • Time: O(n + m) with KMP.
  • Space: O(n + m).
Topic: String Pattern Matching
🎬 Episodes 18–19: video coming soon