Repeated Substring Pattern
Given a string s, determine if it can be constructed by taking a substring of it and appending multiple copies of that substring together. Return true if such a pattern exists, false otherwise.
For example, "abab" can be constructed from "ab" repeated twice — return true. "abcabcabc" can be constructed from "abc" repeated three times. "aba" cannot be constructed from any repeated substring — return false. An empty or single-character string returns false.
This problem tests string pattern matching and divisor-based reasoning. The repeating substring's length must divide the total string length evenly. Once a candidate length is found, check if the substring repeats to form the full string.
The solution iterates through possible substring lengths that divide the total length. For each candidate length, take the prefix of that length and check if repeating it forms the full string.
Edge cases include an empty string (false), single character (false), a string that is exactly two repeats of a pattern (true), and a string where no divisor length works (false).
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
Check each divisor length to see if repeating the prefix forms the full string.
Loop through possible pattern lengths from 1 to n/2. If the length divides the total length evenly, build a string by repeating the prefix of that length. Compare the built string to the original. If they match, return true. If no length works, return false.
Time complexity is O(n^2) in the worst case, space complexity is O(n).
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.
