Repeat String Problem
Description
LeetCode Problem 2796.
Write code that enhances all strings such that you can call the string.replicate(x) method on any string and it will return repeated string x times.
Try to implement it without using the built-in method string.repeat.
Example 1:
Input: str = "hello", times = 2
Output: "hellohello"
Explanation: "hello" is repeated 2 times
Example 2:
Input: str = "code", times = 3
Output: "codecodecode"
Explanation: "code" is repeated 3 times
Example 3:
Input: str = "js", times = 1
Output: "js"
Explanation: "js" is repeated 1 time
Constraints:
1 <= times <= 10^51 <= str.length <= 1000
Follow up: Let's assume, for the sake of simplifying analysis, that concatenating strings is a constant time operation O(1). With this assumption in mind, can you write an algorithm with a runtime complexity of O(log n)?
Solution
Approach: Doubling the string (binary exponentiation)
Add replicate to String.prototype. Inside it, this is the string being repeated.
The simple way is to append the string times times. The follow-up asks for O(log n) concatenations, which works like fast exponentiation:
- Keep
base(initially the string) andresult(initially empty). - Look at the bits of
timesfrom the lowest. If the bit is set, appendbasetoresult. Then doublebase(base += base) and shifttimesright. - After the last bit,
resultholds the string repeated exactlytimestimes.
For example, times = 5 = 101 in binary appends base at the first step, skips base+base, and appends 4 * base at the third.
Complexity: Time O(log n) concatenations (not counting the cost of copying characters), space O(n * len) for the result.
/**
* @param {number} times
* @return {string}
*/
String.prototype.replicate = function (times) {
let base = String(this);
let result = '';
while (times > 0) {
if (times & 1) result += base;
base += base;
times >>= 1;
}
return result;
};