Reverse String II — LeetCode 541 Python Solution
- Problem
- #541
- Pattern
- Two Pointers
- Reading time
- 2 min
- Source
- leetcode.com
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
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
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(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.