Repeat String - Problem
In this problem, you'll extend JavaScript's String prototype to add a custom method that repeats a string multiple times.
Goal: Implement a String.prototype.replicate(x) method that returns the string repeated x times. For example, "hello".replicate(3) should return "hellohellohello".
Challenge: You must implement this without using the built-in String.prototype.repeat() method. This exercise will help you understand string manipulation, prototype extension, and algorithm optimization.
Examples:
• "abc".replicate(2) → "abcabc"
• "x".replicate(5) → "xxxxx"
• "hello".replicate(0) → ""
Input & Output
example_1.js — Basic Usage
$
Input:
"hello".replicate(3)
›
Output:
"hellohellohello"
💡 Note:
The string 'hello' is repeated 3 times consecutively without any separators.
example_2.js — Single Character
$
Input:
"x".replicate(5)
›
Output:
"xxxxx"
💡 Note:
Single character 'x' is repeated 5 times to create a string of length 5.
example_3.js — Edge Case Zero
$
Input:
"test".replicate(0)
›
Output:
""
💡 Note:
When repeat count is 0, the method should return an empty string regardless of the original string.
Constraints
-
The repeat count
xwill be a non-negative integer (0 ≤ x ≤ 1000) - The original string length will not exceed 100 characters
-
Cannot use the built-in
String.prototype.repeat()method -
Must extend the String prototype to add the
replicatemethod
Visualization
Tap to expand
Understanding the Visualization
1
Simple Approach
Worker copies 'abc' five times: abc + abc + abc + abc + abc
2
Smart Approach Setup
Machine starts with 'abc', target is 5 copies (binary: 101)
3
Binary Logic
101 means: take 1×'abc' + skip 2×'abc' + take 4×'abc'
4
Efficient Result
Result: 'abc' + 'abcabcabcabc' = 'abcabcabcabcabc'
Key Takeaway
🎯 Key Insight: Binary exponentiation transforms a linear problem into a logarithmic one by leveraging the binary representation of the repeat count, making it exponentially faster for large inputs.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code