Repeated Substring Pattern (LeetCode 459): Solution and Explanation

Easy
String
String matching

Decide whether s is some shorter block written two or more times in a row. "abab" is "ab" twice, so the answer is true; "aba" cannot be built that way.

Intuition

Suppose s is a block p repeated, like abab = ab + ab. Move the first p to the end: you get ab + ab again. So rotating s by the block length gives back s.

The reverse is also true: if rotating s left by some k with 0 < k < n gives s back, then s[i] = s[i + k] all the way around, and s is built from repeats of its first gcd(n, k) characters.

Every rotation of s is a window of length n inside s + s. The windows at shift 0 and shift n are s itself and prove nothing, so cut the first and last character of s + s to remove them. If s still appears, a real rotation matched.

Approach: Search s inside the trimmed s + s

  1. Build doubled = s + s.
  2. Drop its first and last character: trimmed = doubled[1 : 2n - 1].
  3. Return whether s occurs in trimmed.

Step-by-step example

s = "abab"
  1. doubled = abababab.
  2. Trim both ends: bababa. The windows left are shifts 1, 2 and 3.
  3. Shift 1: the window is baba, which differs from abab at the first character.
  4. Shift 2: the window is abab, which equals s. So s is ab repeated twice.
  5. The search finds s, so the answer is true.

Code: Python, Java, C++

1class Solution:
2    def repeatedSubstringPattern(self, s: str) -> bool:
3        doubled = s + s
4        trimmed = doubled[1:-1]
5        return trimmed.find(s) != -1
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Building the doubled string is linear and a linear-time search (KMP or Z-function) finds s in it. Library substring searches are fast in practice.

Space

O(n)

The doubled string has length 2n.

Other approaches

Try every divisor length (time O(n * d(n)), space O(n))

For each k that divides n with k < n, check whether s[:k] repeated n / k times equals s. Simple and fast enough because n has few divisors.

KMP prefix function (time O(n), space O(n))

Compute the longest proper prefix that is also a suffix, L. The answer is true when L > 0 and n % (n - L) == 0; then n - L is the smallest period.

Common mistakes

  • Forgetting to trim. s always occurs in s + s at shift 0, so without trimming every string would return true.
  • Trimming only one end. The window at shift n is also s, so the last character must go too.
  • Counting a single copy as a repetition. The block must appear at least twice, which is why a one-character string returns false.

Frequently asked questions

Why does a matching rotation prove the string is periodic?

If rotating by k gives s back, then s[i] = s[(i + k) mod n] for every i. Following that rule shows every character equals the one gcd(n, k) positions later, so s is its first gcd(n, k) characters repeated, and gcd(n, k) < n.

Where does the trick find the block length?

The first index where s appears in the trimmed string, plus one, is the smallest shift that reproduces s. That shift is the shortest repeating block.

Is the library search really linear?

Not always in the worst case, but it is fast in practice. For a guaranteed O(n) bound, run KMP of s against the trimmed string, or use the prefix-function formula directly.