EasyNo. 2796LeetCode Premium

Repeat String — LeetCode 2796 Python Solution

Topics
JavaScript
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

PythonSolution
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

Time
O(k)where k is the output length
Space · auxiliary
O(k)

Related problems

Related problems
No.ProblemDifficulty
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy

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.

Free to download. Check it runs on your machine, then pick a plan.