Repeated Substring Pattern
Easy · Arrays & Hashing · Explanation and code example
Search Inside a Doubled String
How it works
If a string consists of repeated copies of a shorter block, rotating it by one block produces the same string. Doubling the string contains all such rotations. Removing the first and last positions excludes the two trivial matches, leaving a match exactly when a proper repeat exists.
Steps
- Build s + s.
- Remove its first and last characters.
- Check whether s occurs in the remaining string.
Complexity
- Time: Conservative O(n²) worst-case substring search; library implementations may be faster.
- Space: O(n) for the doubled string and substring.
Things to watch for
- Exclude both trivial boundary matches.
- A one-character string cannot repeat a shorter nonempty block.
- The returned answer is a boolean, not the repeated block.
Python code example
class Solution:
def repeatedSubstringPattern(self, s: str) -> bool:
return s in (s + s)[1:-1]
C++ code example
class Solution {
public:
bool repeatedSubstringPattern(string s) {
const string ss = s + s;
return ss.substr(1, ss.length() - 2).find(s) != string::npos;
}
};
Source and license
Explanation by LC Tracker. Code adapted from walkccc / Peng-Yu Chen · MIT license. Node types are supplied by LeetCode where needed.