15% off all plans & roadmaps Use code
See plansLeetCode 686 · Solution & editorial
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 a after repeating it, return -1.
Repeated String Match is a String Manipulation Patterns problem, in the Naive / KMP / Rabin-Karp subpattern. The pattern covers palindrome checking, anagram detection, pattern matching, and string conversion
Master string matching algorithms including naive search, KMP pattern matching, and Rabin-Karp hashing.
The reference solution runs in O((n + m) * n) time and O(n + m) space.
Repeated String Match has been reported in interviews at Google, Facebook, Amazon.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Repeated String Match is a String Manipulation Patterns problem, in the Naive / KMP / Rabin-Karp subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.