Problem Description
Determine if a given string can be constructed by taking a substring of it and appending multiple copies of that substring together.
Key Insights
- The repeated substring must be a divisor of the entire string's length.
- A trick uses string manipulation by checking if the string exists in (s+s) with its first and last characters removed.
- Alternatively, iterate through all possible substring lengths (that are divisors of the total length) and check if repeating the substring yields the original string.
Space and Time Complexity
Time Complexity: O(n^2) in the worst case if checking each possible candidate manually, but the trick method runs in O(n).
Space Complexity: O(n) due to the extra temporary string created in the trick method.
Solution
We can solve the problem using one of two approaches:
- Brute-force: Try each possible substring whose length divides the original string length. For each candidate, repeat it and compare with the original string.
- Trick approach: Form a new string by concatenating the original string with itself and remove the first and last characters. Then check if the original string exists in this modified string. If it does, the original string is composed of repeated substrings.
The trick approach is more elegant and efficient. It leverages the fact that a repeated pattern will appear at least twice in the overlapped string.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with line-by-line comments.