Reverse String II — LeetCode 541 Python Solution

EasyTwo PointersString
Problem
#541
Reading time
2 min

The problem

Given a string s and an integer k, reverse the first k characters for every 2k characters counting from the start of the string. If there are fewer than k characters left, reverse all of them.

Example

Input
s = "abcdefg", k = 2
Output
"bacdfeg"

Python solution

Python
class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        cs = list(s)
        for i in range(0, len(cs), 2 * k):
            cs[i : i + k] = reversed(cs[i : i + k])
        return "".join(cs)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Two Pointers

Use the order already in the input to discard half the search space at every step. LeetCode 541. Reverse String II is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.

The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 541. Reverse String II?
LeetCode 541. Reverse String II is rated Easy on LeetCode.
What is the time complexity of LeetCode 541. Reverse String II?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 541. Reverse String II?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 541. Reverse String II cover?
LeetCode 541. Reverse String II is tagged Two Pointers and String on LeetCode.

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