Problem Statement
Given a string s, determine whether it can be constructed by repeating a substring of itself.
Return true if the string can be formed by repeating a substring, otherwise return false.
Example
Input: "abab"
Output: true
Explanation: "ab" repeated 2 times
Input: "abcabcabc"
Output: true
Explanation: "abc" repeated 3 times
Input: "aba"
Output: false
Input: "aaaa"
Output: true
Explanation: "a" repeated 4 times
Understanding the Problem
We need to check if a smaller substring repeats multiple times to form the entire string.
Example:
"abcabcabc"
Possible repeating substring:
"abc"
If we repeat "abc" three times:
"abcabcabc"
This matches the original string, so the answer is true.
But consider:
"aba"
There is no substring that can repeat to form "aba", so the answer is false.
Brute Force Approach
The simplest way to solve this problem is to try every possible substring and check if repeating it forms the original string.
Important observation:
The repeating substring length must divide the length of the string.
Example:
String = "abab"
Length = 4
Possible substring lengths:
1
2
Now test them.
Substring "a":
"a".repeat(4) → "aaaa" ❌
Substring "ab":
"ab".repeat(2) → "abab" ✅
So "ab" is the repeating substring.
Algorithm
- Get the length of the string.
- Iterate through all possible substring lengths from
1tolength / 2. - If the string length is divisible by the substring length:
- Extract the substring.
- Repeat it enough times to match the original length.
- Compare it with the original string.
- If a match is found → return
true. - Otherwise return
false.
- If a match is found → return
JavaScript Implementation
var repeatedSubstringPattern = function(s) {
let len = s.length;
for (let i = 1; i <= len / 2; i++) {
if (len % i === 0) {
let sub = s.slice(0, i);
if (sub.repeat(len / i) === s) {
return true;
}
}
}
return false;
};
Testing the Solution
console.log(repeatedSubstringPattern("abcabcabcabc"));
// true
console.log(repeatedSubstringPattern("aba"));
// false
console.log(repeatedSubstringPattern("abab"));
// true
console.log(repeatedSubstringPattern("aaaa"));
// true
Dry Run Example
Let’s test the string:
"ababab"
Length:
6
Possible substring lengths:
1, 2, 3
Check each one.
Substring "a":
"a".repeat(6) → "aaaaaa" ❌
Substring "ab":
"ab".repeat(3) → "ababab" ✅
So the function returns true.
Time Complexity
O(n²)
Because we test multiple substring lengths and perform string comparisons.
Top comments (0)