Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Is the string a combination of repeated substrings in JavaScript
We need to write a JavaScript function that checks if a string can be constructed by repeating a substring multiple times. This is useful for pattern detection in strings.
Problem Statement
Given a string, determine if it consists of a repeated pattern. For example, "abcabcabc" is made by repeating "abc" three times, while "abcdef" has no repeating pattern.
Example Input and Output
For the string:
const str = 'thisthisthisthis';
The expected output is:
const output = true;
Because the string is constructed by repeating 'this' four times.
Solution Using Pattern Division
We can solve this by checking if the string can be evenly divided into identical substrings:
const str = 'thisthisthisthis';
const repeatedSubstring = (str = '') => {
const {length} = str;
// Helper function to check if a substring pattern repeats
const checkSubString = ss => {
const m = ss.length;
for (let i = 0; i = 1) {
while (length % factor) factor++;
len = length / factor;
if (checkSubString(str.substring(0, len))) {
return true;
}
factor++;
}
return false;
};
console.log(repeatedSubstring(str));
true
Alternative Solution Using String Concatenation
A simpler approach uses string concatenation to check if the original string appears in a doubled version:
const isRepeatedPattern = (str) => {
// If string length is 1, it can't be repeated
if (str.length
true
true
false
true
How the Algorithm Works
The pattern division method:
- Finds all factors that divide the string length evenly
- For each factor, extracts a potential pattern substring
- Checks if repeating this pattern recreates the original string
The concatenation method works because if a string has a repeating pattern, it will appear in the doubled string at a position other than the start and end.
Comparison of Methods
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Pattern Division | O(n²) | O(1) | Complex |
| String Concatenation | O(n) | O(n) | Simple |
Conclusion
Both methods effectively detect repeated substring patterns. The concatenation approach is simpler and more efficient, while the division method provides better insight into the actual repeating pattern.
