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 x will 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 replicate method

Visualization

Tap to expand
String Replication: Simple vs Binary ApproachSimple Loop ApproachStep 1: result = "" + "abc" = "abc"Step 2: result = "abc" + "abc" = "abcabc"Step 3: result = "abcabc" + "abc" = "abcabcabc"Step 4: result = "abcabcabc" + "abc" = "abcabcabcabc"Step 5: result = "abcabcabcabc" + "abc" = "abcabcabcabcabc"5 operations, O(n²) complexityBinary Exponentiationx = 5 (binary: 101)Bit 0 (1): result += "abc" → "abc"Bit 1 (0): skip, base = "abcabc"Bit 2 (1): result += "abcabcabcabc"Final: "abc" + "abcabcabcabc" = "abcabcabcabcabc"3 operations, O(n log m) complexityPerformance ComparisonSimple: O(n²)Binary: O(n log m)For large repeat counts, binary approach is significantly faster!Both produce same result
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.
Asked in
Google 15 Meta 12 Amazon 8 Microsoft 6
23.4K Views
Medium Frequency
~12 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen