Skip to content
Problem 686 · LeetCode 686(opens in a new tab)

Repeated String Match

MediumString matching

You get two lowercase strings, a and b. Write a out several times in a row, with nothing between the copies, and you get a longer string.

Return the fewest copies of a you need so that b shows up somewhere inside the result as a contiguous piece. If no number of copies works, return −1.

Example 1

Input:  a = "xyz", b = "zxyzx"
Output: 3
Why:    "xyzxyzxyz" holds b at index 2; two copies end too soon
2 more examples and the constraints

Example 2

Input:  a = "pqrs", b = "rs"
Output: 1
Why:    b already sits inside a single copy

Example 3

Input:  a = "mno", b = "mon"
Output: -1
Why:    after an m the copies always read n, never o

Constraints

  • 1 ≤ a.length ≤ 10,000
  • 1 ≤ b.length ≤ 10,000
  • Both strings use only the letters a to z

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Try each countO(m²/n + m)
  2. One KMP passO(n + m)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for a of 1 letter and b of 10,000Verdict
Try each countO(m²/n + m)
Simple; rebuilds the text every try
One KMP passO(n + m)
Best; one scan, no copies built

n = length of a, m = length of b.

Edge cases to test

  • b inside one copy. a = "pqrs", b = "rs" gives 1. Do not start counting at 2.
  • b equals a. a = "abc", b = "abc" gives 1.
  • A letter a lacks. If b uses any letter not in a, no count works: −1.
  • b shorter than a, but split. a = "abcd", b = "da" needs 2 copies even though b is short.
  • One-letter a. a = "q", b = 10,000 q's needs exactly 10,000 copies.

Common mistakes

  • Stopping at ceil(m / n) copies; the match may start late in a copy and need one more.
  • Returning −1 too early when b is shorter than a but wraps across the seam of two copies.
  • Looping with no upper bound on the count, which never ends when the answer is −1.

How to talk through it

  1. 1Clarify. Does zero copies count? Can b be shorter than a? Are both strings non-empty?
  2. 2Bound the copies. A match can start inside the first copy, so it ends before n + m: at most m / n + 2 copies.
  3. 3Give the simple version. Try each k up to that bound with a built-in search. Correct, but it rebuilds the text each time.
  4. 4Make it linear. Run KMP once over the virtual text a[i % n] and return the copy where the first match ends.
  5. 5Test out loud. Run b inside one copy, b across a seam, a missing letter, and a one-letter a.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?