> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Reverse String II Python Solution with Tests

> Tested Python solution for LeetCode 541 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 541, [Easy](/catalog/easy). Topics: [Two Pointers](/catalog/topics/two-pointers), [String](/catalog/topics/string). [View on LeetCode](https://leetcode.com/problems/reverse-string-ii/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 541   # by problem number
lcpy gen -s reverse_string_ii   # by problem name
```

## 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. If there are less than `2k` but greater than or equal to `k` characters, then reverse the first `k` characters and leave the other as original.

### Examples

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

```
Input: s = "abcd", k = 2
Output: "bacd"
```

### Constraints

* 1 \<= s.length \<= 10^4
* s consists of only lowercase English letters.
* 1 \<= k \<= 10^4

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/reverse_string_ii/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/reverse_string_ii/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n)
    # Space: O(n)
    def reverse_str(self, s: str, k: int) -> str:
        chars = list(s)
        for i in range(0, len(chars), 2 * k):
            chars[i : i + k] = reversed(chars[i : i + k])
        return "".join(chars)
```

## Complexity

| Time | Space |
| - | - |
| O(n) | O(n) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.