Repeated Substring Pattern (LeetCode 459): Solution and Explanation
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
- Build
doubled = s + s. - Drop its first and last character:
trimmed = doubled[1 : 2n - 1]. - Return whether
soccurs intrimmed.
Step-by-step example
s = "abab"
- doubled =
abababab. - Trim both ends:
bababa. The windows left are shifts 1, 2 and 3. - Shift 1: the window is
baba, which differs fromababat the first character. - Shift 2: the window is
abab, which equalss. Sosisabrepeated twice. - The search finds
s, so the answer istrue.
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) != -11class Solution {
2 public boolean repeatedSubstringPattern(String s) {
3 String doubled = s + s;
4 String trimmed = doubled.substring(1, doubled.length() - 1);
5 return trimmed.contains(s);
6 }
7}1class Solution {
2public:
3 bool repeatedSubstringPattern(string s) {
4 string doubled = s + s;
5 string trimmed = doubled.substr(1, doubled.size() - 2);
6 return trimmed.find(s) != string::npos;
7 }
8};Time and space complexity
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.
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.
salways occurs ins + sat shift 0, so without trimming every string would returntrue. - 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.