Repeat String — LeetCode 2796 Python Solution

EasyLeetCode PremiumJavaScript
Problem
#2796
Reading time
2 min

The 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.

Example

Input
str = "hello", times = 2
Output
"hellohello"
Explanation
"hello" is repeated 2 times

Python solution

Python
class Solution:
    def replicate(self, s: str, times: int) -> str:
        if times <= 0:
            return ""
        parts = []
        for _ in range(times):
            parts.append(s)
        return "".join(parts)

Complexity

MeasureComplexity
TimeO(k) where k is the output length
SpaceO(k) auxiliary

Related problems

Frequently asked questions

How hard is LeetCode 2796. Repeat String?
LeetCode 2796. Repeat String is rated Easy on LeetCode.
What is the time complexity of LeetCode 2796. Repeat String?
The Python solution on this page runs in O(k) where k is the output length.
What is the space complexity of LeetCode 2796. Repeat String?
The Python solution on this page uses O(k) auxiliary space.
What topics does LeetCode 2796. Repeat String cover?
LeetCode 2796. Repeat String is tagged JavaScript on LeetCode.
Is LeetCode 2796. Repeat String a premium problem?
Yes. LeetCode 2796. Repeat String is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview