easy Repeated Substring Pattern
Problem Statement
Given a string s, return true if it can be formed by taking any substring of it and appending multiple copies of the substring together.
A substring is a contiguous sequence of characters in the string.
Examples
-
Example 1:
- Input: s =
"bcdbcdbcdbcd" - Expected Output:
true - Justification: The input string can be formed by repeating the substring
"bcd"three times.
- Input: s =
-
Example 2:
- Input: s =
"abcdabcd" - Expected Output:
true - Justification: The input string is the result of the substring
"abcd"repeated twice.
- Input: s =
-
Example 3:
- Input: s =
"aabaaba" - Expected Output:
false - Justification: There's no single substring that, when repeated, forms the input string.
- Input: s =
Try it yourself
Try solving this question here:
✅ Solution Repeated Substring Pattern
Problem Statement
Given a string s, return true if it can be formed by taking any substring of it and appending multiple copies of the substring together.
A substring is a contiguous sequence of characters in the string.
Examples
-
Example 1:
- Input: s =
"bcdbcdbcdbcd" - Expected Output:
true - Justification: The input string can be formed by repeating the substring
"bcd"three times.
- Input: s =
-
Example 2:
- Input: s =
"abcdabcd" - Expected Output:
true - Justification: The input string is the result of the substring
"abcd"repeated twice.
- Input: s =
-
Example 3:
- Input: s =
"aabaaba" - Expected Output:
false - Justification: There's no single substring that, when repeated, forms the input string.
- Input: s =
Solution
To solve this problem, we can utilize the concept of string manipulation and iteration. The intuition behind the solution is that if the string can indeed be constructed by repeating a substring, then this pattern should be identifiable by analyzing the structure of the string itself. Essentially, we'll try to find a smaller, repeating pattern within the string that, when extended, recreates the original string.
The most effective approach involves checking each possible substring length from 1 up to half the length of the string (since a repeating substring would be at most half the length of the original string). For each possible length, we replicate the substring and check if it matches the original string. This method is both straightforward and efficient for identifying repeating patterns within strings.
Step-by-Step Algorithm
-
Determine the length of the input string (
s): Calculate the length ofsand store it. This length will be used to limit the possible lengths of the repeating substring. -
Iterate over possible substring lengths: Loop from 1 up to half the length of
s. The rationale is that a repeating substring can be at most half the length ofs, because to repeat, the substring needs to appear at least twice. -
Check divisibility: For each length
i, check if the total length ofsis divisible byi. This step ensures thatscan be evenly divided into substrings of lengthi. -
Extract and repeat the substring: If the length is divisible, extract a substring of length
istarting from the beginning ofs. Repeat this substring enough times so that the concatenated result has the same length ass. -
Compare the constructed string with the original: Check if the repeated substring, when concatenated together, equals the original string
s. If they match, it meansscan indeed be formed by repeating a substring, and you returntrue. -
Continue the iteration: If no match is found, continue the iteration with the next possible length.
-
Return false: If the loop finishes without finding any repeating substring pattern that can form
s, returnfalse.
Algorithm Walkthrough
Let's consider the input: s = "bcdbcdbcdbcd"
-
Length Calculation:
- The length of
sis 12.
- The length of
-
Iteration Over Possible Substring Lengths:
- The possible lengths to check are 1 to 6 (half of 12).
-
Length 1 (i=1):
- Check if 12 is divisible by 1 (yes).
- Repeat "b" 12 times.
- The result "bbbbbbbbbbbb" does not match
s.
-
Length 2 (i=2):
- Check if 12 is divisible by 2 (yes).
- Repeat "bc" 6 times.
- The result "bcbcbcbcbcbc" does not match
s.
-
Length 3 (i=3):
- Check if 12 is divisible by 3 (yes).
- Repeat "bcd" 4 times.
- The result "bcdbcdbcdbcd" matches
s. - Return
truebecause we found thatscan be formed by repeating "bcd".
Code
public class Solution {
// Method to check if the string can be formed by repeating a substring
public boolean repeatedSubstringPattern(String s) {
int len = s.length();
// Loop over possible substring lengths, up to half the length of s
for (int i = len / 2; i >= 1; i--) {
if (len % i == 0) { // Only consider i if it's a divisor of len
String pattern = s.substring(0, i);
StringBuilder sb = new StringBuilder();
// Repeat the pattern to match the length of s
for (int j = 0; j < len / i; j++) {
sb.append(pattern);
}
if (sb.toString().equals(s)) { // Check if the repeated pattern matches s
return true;
}
}
}
return false; // Return false if no repeating pattern is found
}
public static void main(String[] args) {
Solution solution = new Solution();
// Example 1
System.out.println(solution.repeatedSubstringPattern("bcdbcdbcdbcd")); // true
// Example 2
System.out.println(solution.repeatedSubstringPattern("abcdabcd")); // true
// Example 3
System.out.println(solution.repeatedSubstringPattern("aabaaba")); // false
}
}
Complexity Analysis
- Time Complexity:
in the worst case, because for each substring length up to n/2, we're constructing a new string and comparing it to the original string, each operation taking time. - Space Complexity:
, where n is the length of the input string. This is because we are creating a new string to compare with the original string.
🤖 Don't fully get this? Learn it with Claude
Stuck on Repeated Substring Pattern? Open Claude, copy a block below, and it'll teach you this exact concept — visually and interactively.
Progressively stronger hints — you still solve it.
I'm working on the problem **Repeated Substring Pattern** (DSA). Give me a HINT LADDER: start with the tiniest nudge, then wait. Only reveal the next, stronger hint when I ask. Do NOT show the full solution unless I type 'show solution'. Keep me doing the thinking. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
See the technique, not just code.
Explain the optimal approach to **Repeated Substring Pattern** with a VISUAL walkthrough: trace it on a small concrete example using ASCII art / a step-by-step diagram, narrate what changes each step, then give time & space complexity with a one-line derivation. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Catch bugs, edge cases, sub-optimality.
I'll paste my solution to **Repeated Substring Pattern**. Review it for correctness, missed edge cases, and time/space complexity, then coach me toward the optimal — don't just rewrite it. Ask me to paste my code now. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.
Lock in recognition with look-alikes.
Give me 2 problems that use the SAME underlying pattern as **Repeated Substring Pattern**. For each, let me attempt first, then review my answer and name the trigger signal that reveals the pattern. If you're unsure or a claim isn't standard, say so and reason from first principles instead of guessing.