Repeat String - 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.

Note: Try to implement it without using the built-in method string.repeat.

This problem requires extending the String prototype in JavaScript to add a custom method that replicates the string functionality.

Input & Output

Example 1 — Basic Repetition
$ Input: str = "abc", times = 3
Output: abcabcabc
💡 Note: String 'abc' repeated 3 times gives 'abcabcabc'
Example 2 — Single Character
$ Input: str = "x", times = 5
Output: xxxxx
💡 Note: Single character 'x' repeated 5 times gives 'xxxxx'
Example 3 — Zero Repetitions
$ Input: str = "hello", times = 0
Output:
💡 Note: Any string repeated 0 times gives empty string

Constraints

  • 1 ≤ str.length ≤ 1000
  • 0 ≤ times ≤ 100

Visualization

Tap to expand
Repeat String - String Concatenation INPUT String to repeat: "a" "b" "c" "abc" Repetition count: 3 str = "abc" times = 3 "abc".replicate(3) ALGORITHM STEPS 1 Initialize result = "" (empty) 2 Loop x times for i = 0 to times-1 3 Concatenate result = result + str 4 Return result return result string Iteration Progress: i=0: "abc" i=1: "abcabc" i=2: "abcabcabc" FINAL RESULT Repeated String: abc abc abc 1st 2nd 3rd "abcabcabc" OK Output: "abcabcabc" Length: 9 chars (3 x 3 = 9) Key Insight: String.prototype.replicate extends ALL strings with a custom method. Each iteration appends the original string to the result. Time complexity: O(n * m) where n = times, m = str.length. TutorialsPoint - Repeat String | String Concatenation per Iteration
Asked in
Google 15 Microsoft 12
23.0K Views
Medium Frequency
~15 min Avg. Time
890 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