Implement String. prototype. repeat() with O(log n) concatenations by doubling
Problem
"ab".repeat(3) returns "ababab". Write repeatString(str, count), which behaves like String.prototype.repeat, without using repeat, padStart, padEnd or Array(n).join.
repeatString("ab", 3); // "ababab"
repeatString("ha", 0); // ""
repeatString("x", 2.9); // "xx" (truncated to 2)
repeatString("x", -1); // RangeErrorRef. UR-1432 · © UIRound · uiround.com/questions/implement-string-prototype-repeat-with-log-n-concatenations-by-doubling
Unlock this question
The full problem, its tests and the tested solution are part of Pro.
- 2
- code listings
- 5
- edge cases
What's inside
- The full problem, with examples
- Tests that check your solution
- Step-by-step
- Approach
- Solution
- Complexity
- Edge cases
- Follow-up questions
- Card worldwide
- UPI and net banking in India
- One-time payment, nothing renews
Stuck? Take a hint
- 1A loop that appends the string count times is correct but does count concatenations. Think of how fast exponentiation squares the base: you can double the string instead.
Try it in the editor
Run your code as often as you like. Submitting it to the full test suite is part of Pro.
Private, and saved in this browser as you type. All your notes are on My lists.