Repeated Substring Pattern
Given a string s, check if it can be constructed by taking a substring of it and appending multiple copies of that substring together. For example, "abab" can be made by repeating "ab" twice, but "aba" cannot.
The trick: concatenate s with itself, remove the first and last character, and check if s appears in the result. If s is a repeating pattern, the doubled string without the ends will contain s. This works because any repeating string s = pattern * k will appear at position p where p equals the pattern length.
Time complexity is O(n) for the contains check. Space is O(n) for the doubled string.
Example Input & Output
"ab" repeated twice
Cannot be formed by repeating a substring
Single char cannot be formed by repeating
Empty string
"abc" repeated 3 times
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public boolean solution(String s) {
return s.length()>1&&(s+s).substring(1,2*s.length()-1).contains(s);
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
