Problem Description
Enhance all strings such that a new method replicate(x) can be called on any string, returning the string repeated x times. You cannot use the built-in repeat method. Additionally, assume that string concatenation is O(1) and aim for an algorithm with runtime complexity O(log n).
Key Insights
- Use an algorithm that employs doubling (binary exponentiation-style) to achieve O(log n) time complexity.
- On each iteration, if the current power bit is set (i.e. times is odd), concatenate the current portion to the result.
- Double the string (i.e. current = current + current) and halve the number of repetitions.
- This approach minimizes the number of concatenations required.
Space and Time Complexity
Time Complexity: O(log n) — because we reduce the number of iterations by half on each step. Space Complexity: O(m * n) in worst case where m is the length of the string and n is the number of times (assuming the concatenated result occupies that much space).
Solution
The solution uses a doubling strategy similar to fast exponentiation. We maintain two variables: one for the final result and one for the current string segment. As we loop while times > 0, we check if the current repetition count is odd. If yes, we append the current segment to the result. Then we double the current segment (i.e., replicate it by itself) and halve the count. This efficiently builds the final repeated string in O(log times) iterations under the given assumption that concatenation operates in constant time.