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
Can one string be repeated to form other in JavaScript
We are required to write a JavaScript function that takes in two strings, str1 and str2, as the first and the second argument.
Our function should return the minimum number of times we should repeat string str1 so that string str2 is a substring of it. If it is impossible for str2 to be a substring after repeating it, we should return -1.
Problem Example
For example, if the input to the function is:
const str1 = 'wxyz'; const str2 = 'yzwxyzwx';
The expected output is 3, because by repeating str1 three times ("wxyzwxyzwxyz"), str2 becomes a substring of it.
Solution Approach
The algorithm works by repeatedly concatenating str1 until str2 is found as a substring. We set a reasonable limit to avoid infinite loops when it's impossible to form str2.
const str1 = 'wxyz';
const str2 = 'yzwxyzwx';
const countRepeat = (str1 = '', str2) => {
let i = 1;
let current = str1;
while (true) {
if (current.indexOf(str2) >= 0) {
return i;
}
// If current length exceeds reasonable limit, return -1
if ((current.length > str2.length * 2) && i > 2) {
return -1;
}
current += str1;
i += 1;
}
};
console.log(countRepeat(str1, str2));
3
How It Works
1. Start with one copy of str1 and increment counter
2. Check if str2 is a substring using indexOf()
3. If found, return the counter
4. If not found and we've exceeded reasonable attempts, return -1
5. Otherwise, concatenate str1 again and continue
Edge Cases
// Case 1: Impossible to form
console.log(countRepeat('ab', 'xyz')); // -1
// Case 2: str2 is already in str1
console.log(countRepeat('abcd', 'bc')); // 1
// Case 3: Empty strings
console.log(countRepeat('abc', '')); // 1
-1 1 1
Conclusion
This solution efficiently finds the minimum repetitions needed by incrementally building the repeated string and checking for substring matches. The algorithm handles edge cases and prevents infinite loops with a reasonable termination condition.
