LeetCode #459 Easy

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.

Constraints
  • 1 <= s.length <= 10⁴
  • s consists of lowercase English letters.
stringstring-matching
Open on LeetCode ↗
02

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]:

  • p divides n: the first p letters, repeated n / p times, rebuild s.
  • It does not, or the border is 0: the last copy would be cut short, so no block length works.
How to spot this pattern

"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.

03

Approach

Try it first

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).

1

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.

2

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.

3

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.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def repeatedSubstringPattern(self, s):
▶3 n = len(s)
▶4 lps = [0] * n
▶5 k = 0
▶6 for i in range(1, n):
▶7 while k > 0 and s[i] != s[k]:
▶8 k = lps[k - 1]
▶9 if s[i] == s[k]:
▶10 k += 1
▶11 lps[i] = k
▶12 p = n - lps[-1]
▶13 return lps[-1] > 0 and n % p == 0
slpsa00b1c2a3b4c5a6b7c8lps of index 0 is 0 → start at index 1
n9
k0current border length
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.
slpsa0k0b1i0c2a3b4c5a6b7c8'b' ≠ 'a' → no border, lps is 0
i1
k0
lps[1]0
b does not match the first letter a, and there is no shorter border left to try. No prefix ends here, so lps[1] = 0.
slpsa0k0b10c2i0a3b4c5a6b7c8'c' ≠ 'a' → no border, lps is 0
i2
k0
lps[2]0
c does not match the first letter a, and there is no shorter border left to try. No prefix ends here, so lps[2] = 0.
slpsa0k0b10c20a3i1b4c5a6b7c8'a' matches → border grows to 1
i3
k1
lps[3]1
a at index 3 equals a at index 0, so the border extends by one letter: the prefix a now also ends at index 3.
slpsa00b1k0c20a31b4i2c5a6b7c8'b' matches → border grows to 2
i4
k2
lps[4]2
b at index 4 equals b at index 1, so the border extends by one letter: the prefix ab now also ends at index 4.
slpsa00b10c2k0a31b42c5i3a6b7c8'c' matches → border grows to 3
i5
k3
lps[5]3
c at index 5 equals c at index 2, so the border extends by one letter: the prefix abc now also ends at index 5.
slpsa00b10c20a3k1b42c53a6i4b7c8'a' matches → border grows to 4
i6
k4
lps[6]4
a at index 6 equals a at index 3, so the border extends by one letter: the prefix abca now also ends at index 6.
slpsa00b10c20a31b4k2c53a64b7i5c8'b' matches → border grows to 5
i7
k5
lps[7]5
b at index 7 equals b at index 4, so the border extends by one letter: the prefix abcab now also ends at index 7.
slpsa00b10c20a31b42c5k3a64b75c8i6'c' matches → border grows to 6
i8
k6
lps[8]6
c at index 8 equals c at index 5, so the border extends by one letter: the prefix abcabc now also ends at index 8.
slpsa00b10c20a31b42c53a64b75c86block 'abc' × 3 → true
lps[n − 1]6longest border
p3n − border
resulttrue
The longest border is 6, so the shortest period is 9 − 6 = 3. 3 divides 9, so abc repeated 3 times rebuilds the string: true.
05

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.

▶1class Solution:
▶2 def repeatedSubstringPattern(self, s):
▶3 return s in (s + s)[1:-1]
06

Common pitfalls

Leaving out the border check

✗ Wrong
return n % (n - lps[-1]) == 0
✓ Right
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

✗ Wrong
return lps[-1] > 0
✓ Right
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

✗ Wrong
return s in s + s
✓ Right
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.

07

Edge cases

One letter, e.g. "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.

All letters equal, e.g. "aaaa"

The longest border is 3, so the period is 1 and it divides 4: the block "a" repeated four times, true.

08

Complexity

Time
O(n)
Space
O(n)
The table has n entries. 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.
09

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.