Problem
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
.
Examples
Example 1:
|
|
Example 2:
|
|
Example 3:
|
|
Constraints:
1 <= times <= 10^5
1 <= 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
Method 1 - Prototype Extension (O(n) and O(log n) approaches)
Intuition
We want to add a method to all strings that returns the string repeated x times, without using the built-in repeat. The naive way is to concatenate in a loop (O(n)), but we can do better with exponentiation by squaring (O(log n)).
Approach
O(n) approach:
- Add a method to String.prototype called replicate.
- Use a loop to concatenate the string x times.
O(log n) approach (Follow up):
- Use exponentiation by squaring: double the string and halve the count at each step, appending to result when needed.
Code
|
|
|
|
|
|
Complexity
- ⏰ Time complexity: O(n) for the naive approach, O(log n) for the exponentiation by squaring approach (assuming O(1) string concat).
- 🧺 Space complexity: O(n * m), where n = times, m = str.length (for the result string).