Skip to content
← All posts

Reverse String II: Chunked Reversal Pattern

5 min read
leetcodeproblemeasystrings

LeetCode #541 Reverse String II is one of those problems that sounds tricky at first but becomes simple once you see the pattern. You are given a string s and an integer k. For every 2k characters counting from the start, you reverse the first k characters. If fewer than k characters remain, reverse all of them. If between k and 2k characters remain, reverse the first k and leave the rest as-is.

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.

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

The string is processed in windows of size 2k. Within each window, only the first k characters get reversed. The second half of each window stays in its original order.

0123456abcdefgchunk 0 (2k=4)reverse k=2chunk 1 (2k=4)reverse k=2
s = "abcdefg", k = 2. Blue cells are the first k characters in each 2k chunk that get reversed. White cells remain in place.

The approach

The key insight is that you iterate through the string in steps of 2k. At each step, you reverse the slice from index i to i + k. Python makes this especially clean because slicing handles out-of-bounds gracefully. If the remaining characters are fewer than k, the slice just takes whatever is left.

Here is the algorithm:

  1. Convert the string to a list (strings are immutable in Python).
  2. Loop with a step of 2k, starting at index 0.
  3. At each position i, reverse the subarray from i to i + k.
  4. Join the list back into a string.

That is it. No special cases needed because Python slice semantics naturally handle the edge cases where fewer than k or fewer than 2k characters remain.

The solution

def reverseStr(s: str, k: int) -> str:
    chars = list(s)
    for i in range(0, len(chars), 2 * k):
        chars[i:i+k] = chars[i:i+k][::-1]
    return ''.join(chars)

Let's break it down:

  1. list(s) converts the string to a mutable list of characters.
  2. range(0, len(chars), 2 * k) gives us starting positions 0, 4, 8, ... (jumping by 2k each time).
  3. chars[i:i+k][::-1] takes the first k characters of the current chunk and reverses them.
  4. The slice assignment chars[i:i+k] = ... puts the reversed characters back in place.
  5. ''.join(chars) converts the list back to a string.

Step-by-step walkthrough

Let's trace through s = "abcdefg" with k = 2. The chunk size is 2k = 4, so we process indices [0,4), then [4,8).

Initial: s = "abcdefg", k = 2

0123456abcdefg

We process the string in chunks of 2k = 4. For each chunk, reverse the first k = 2 characters.

Step 1: Process chunk [0, 4). Reverse indices 0 to 1.

0123456bacdefg

First chunk is "abcd". Reverse first 2 chars: "ab" becomes "ba". The rest stays. Result so far: "bacdefg".

Step 2: Process chunk [4, 8). Reverse indices 4 to 5.

0123456bacdfeg

Second chunk is "efg" (only 3 chars left). Reverse first 2 chars: "ef" becomes "fe". Result so far: "bacdfe g".

Final result: "bacdfeg"

0123456bacdfeg

All chunks processed. Final answer: "bacdfeg". Each 2k-sized window had its first k characters reversed.

Notice how clean the logic is. Each iteration does exactly one thing: reverse a slice of length k (or less if we are near the end). No branching, no special cases in the code itself.

Complexity analysis

ApproachTimeSpace
Chunked reversalO(n)O(n)

Time: O(n). We visit every character exactly once across all the chunk reversals. Each reversal of k elements takes O(k) time, and we do n/(2k) reversals, giving O(n/2) total work, which is O(n).

Space: O(n). We create a list copy of the string. In languages with mutable strings (like C++), you can do this in O(1) extra space by reversing in place.

The building blocks

This problem uses one core building block:

Chunk iteration with step size

The pattern of iterating with range(0, n, step) and processing a fixed-size window at each position appears in many problems. The general template is:

for i in range(0, len(arr), chunk_size):
    process(arr[i:i+chunk_size])

For Reverse String II, the chunk size is 2k and the processing is "reverse the first k elements." This same stepping pattern shows up in problems like Rotate Array (processing in groups) and String Compression (walking through runs of characters).

In-place slice reversal

Reversing a subarray between two indices is a fundamental string/array operation:

arr[left:right] = arr[left:right][::-1]

Or equivalently with a two-pointer swap:

while left < right:
    arr[left], arr[right] = arr[right], arr[left]
    left += 1
    right -= 1

This building block appears in Reverse String, Rotate Array, and many other problems that rearrange elements within a fixed range.

Edge cases

Before submitting, verify your solution handles:

  • String shorter than k like s = "ab", k = 3: reverse the entire string. The slice chars[0:3] just takes what exists ("ab"), so reversing gives "ba".
  • String length between k and 2k like s = "abcde", k = 3: reverse the first k = 3 characters ("abc" becomes "cba"), leave the rest. Result: "cbaде".
  • String length exactly 2k like s = "abcd", k = 2: one full chunk, reverse first 2. Result: "bacd".
  • k = 1: every reversal is a single character, so the string stays unchanged. The function returns the original string.
  • k greater than or equal to string length: reverse the entire string, same as the basic Reverse String problem.
  • Single character s = "a": returns "a" unchanged.

The beauty of the slice-based solution is that all of these cases work without any explicit conditionals. Python's slice semantics handle the boundary conditions for you.

In an interview, mention that you are relying on Python's slice behavior to handle edge cases implicitly. This shows awareness of language semantics and avoids cluttering the code with special-case branches.

From understanding to recall

You have seen how Reverse String II works. The algorithm is short: one loop, one slice reversal. But under interview pressure, the details trip people up. What is the step size? Do you reverse i to i+k or i to i+k-1? Is it range(0, n, k) or range(0, n, 2*k)?

These are not conceptual gaps. They are recall gaps. You understand the approach perfectly, but when you sit down to write it, the exact indices feel uncertain.

Spaced repetition fixes this. You write the solution from scratch at increasing intervals. After a few reps, the step size 2*k and the slice chars[i:i+k] are automatic. You stop second-guessing the bounds because your fingers have typed them multiple times before.

Related posts

  • Reverse String - The simpler two-pointer in-place reversal that forms the core building block used here
  • Rotate Array - Another problem where chunked processing and in-place reversals combine to produce the answer
  • String Compression - Uses the same "walk through the string in groups" pattern with a read/write pointer approach

CodeBricks breaks string manipulation problems into their reusable pieces and drills them individually. You practice the chunk iteration pattern, the slice reversal, and the index arithmetic until they flow naturally. When Reverse String II or a similar problem appears in an interview, you write the solution without hesitation.