Repeated Substring Pattern
Repeated Substring Pattern is LeetCode 459 (Easy). Given a string s, return true if it can be built by taking one of its substrings and writing it out two or more times in a row, and false otherwise.
- The block must repeat at least twice, so the whole string on its own does not count.
- The block is always a prefix of
s, since the first copy starts at index 0.
With s up to 10,000 letters, a linear check is easy to reach and avoids trying block lengths one by one.
- 1 <= s.length <= 10⁴
- s consists of lowercase English letters.
Intuition
If s is a block of length p written out several times, then cutting off the first p letters leaves the same text as cutting off the last p. So s has a border: a shorter prefix that is also a suffix, of length n − p.
The KMP prefix table gives the longest border, lps[n − 1], in one pass. The longest border means the shortest block it allows, p = n − lps[n − 1]:
pdividesn: the firstpletters, repeatedn / ptimes, rebuilds.- It does not, or the border is 0: the last copy would be cut short, so no block length works.
"Is this string made of copies of one piece?" is a question about its shortest period, and the period of a string is its length minus its longest border. Any time a problem asks about prefixes that reappear as suffixes, the KMP prefix table is the tool.
Approach
Before reading on, write abcabcabc and find the longest prefix that is also a suffix, without being the whole string. Subtract its length from 9 and look at what you get. Then try the same on abcab. Aim for O(n).
Two ways to solve it
Find the longest border, then check that n − border divides n.
- Always linear, in every language.
- Names the block: it is the first
n − borderletters.
The answer when asked for a guaranteed O(n).
Look for s inside s + s with its first and last letters removed.
- One line in any language.
- Cost: depends on the library search; C++
findand Javacontainscan be quadratic on bad inputs.
The quick answer when nobody asks about the worst case.
The doubling trick is shorter, but its speed is whatever the built-in substring search gives. The prefix table is linear everywhere and shows why the answer is true. The steps, code and live demo follow the prefix table, and the s + s code comes after the demo.
Build the prefix table
lps[i] is the length of the longest prefix of s[0..i] that is also a suffix of it, other than the whole piece. Keep k, the border length so far, and fill the table from left to right, because each entry is built from the one before it.
Grow the border when the letters match
If s[i] == s[k], set k += 1 and store it in lps[i]. The first k letters already ended at i − 1, and the next letter agrees, so that prefix now ends at i and is one letter longer.
Fall back to a shorter border on a mismatch
While k > 0 and s[i] != s[k], set k = lps[k − 1]. Every shorter border that might still grow is a border of the current one, so jumping through the table tries them all in order and skips none.
Test the shortest period
Let b = lps[n − 1] and p = n − b. Return true when b > 0 and n % p == 0, because then the first p letters tile the whole string n / p times. Otherwise return false.
Code in Python, C++ and Java
lps[i] will hold the length of the longest prefix of s[0..i] that is also a suffix of it, without being the whole thing. One letter has no shorter prefix, so lps[0] = 0.lps[i] will hold the length of the longest prefix of s[0..i] that is also a suffix of it, without being the whole thing. One letter has no shorter prefix, so lps[0] = 0.lps[0] = 0, the longest border of the border itself, so no candidate is skipped.lps[i] will hold the length of the longest prefix of s[0..i] that is also a suffix of it, without being the whole thing. One letter has no shorter prefix, so lps[0] = 0.Repeated substring pattern with s + s
s + s contains every rotation of s: the copy that starts at index r is s rotated left by r. A string made of a repeated block equals one of its own rotations, by the block length, which is less than n. Cutting the first and last letter of s + s removes only the two trivial copies at index 0 and index n, so s is still found inside exactly when such a rotation exists.
Common pitfalls
Leaving out the border check
return n % (n - lps[-1]) == 0
return lps[-1] > 0 and n % (n - lps[-1]) == 0
For "abc" the border is 0, so p is 3 and 3 % 3 == 0 says true. That counts the whole string as one copy of itself; a block has to appear at least twice.
Trusting the border without the divisibility test
return lps[-1] > 0
return lps[-1] > 0 and n % (n - lps[-1]) == 0
"abcab" has the border "ab", but its period 3 does not divide 5: the string is abc plus a cut-off ab. A border only proves a period; the block must also fit a whole number of times.
Searching the untrimmed s + s
return s in s + s
return s in (s + s)[1:-1]
s always appears at index 0 of s + s, so this returns true for every input, including "ab". Removing the first and last letter destroys exactly those two trivial copies.
Edge cases
"a"The loop never runs and lps[0] is 0, so the answer is false: a block must appear at least twice, which needs at least two letters.
"aaaa"The longest border is 3, so the period is 1 and it divides 4: the block "a" repeated four times, true.
Complexity
k rises by at most 1 per letter and every fall lowers it, so the falls add up to at most n over the whole loop.Repeated Substring Pattern FAQ
Why is it enough to test only the shortest period?
If some block length d works, then d divides n and is a period. The shortest period p is at most d, and since both are at most n / 2, the two periods make gcd(p, d) a period too (the Fine and Wilf theorem). Since nothing is shorter than p, gcd(p, d) = p, so p divides d and therefore n. So if p fails, every longer block fails as well.
Can you simply try every block length?
Yes. Only lengths that divide n and are at most n / 2 can work, and for each one compare s with its first d letters repeated n / d times. Each check is O(n), and a number up to 10,000 has at most 64 divisors, so this is fast here, though not linear in general.