15% off all plans & roadmaps Use code

See plans

Reverse String II

Updated

TL;DR: Reverse the first k characters of every block of 2k characters, and leave the rest of each block alone. Walk the blocks with a step of 2k. Swap inward with two pointers whose right end is clamped to the string length.

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 fewer than k characters are left at the end, reverse all of them. If the last part has at least k but fewer than 2k characters, reverse its first k characters and leave the rest as it is.

Example 1

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

Example 2

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

Constraints

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

Constraints that matter

  • n up to 10^4 means a single pass is cheap. Nothing here needs more than linear time, and O(n) extra memory is acceptable.
  • Python, Java, JavaScript, Go and C# strings are immutable. You must copy the text into a list, array or byte slice before you can swap characters.
  • k up to 10^4 can be larger than n. Then the step of 2k jumps past the end, so the right boundary must be clamped with a min and the loop must stop cleanly.
  • k can be 1. Each block then reverses one character, which changes nothing. Your code should handle this without a special case.

View on LeetCode

Hints

Hint 1

This problem is a set of independent segment reversals.

Hint 2

A beginner splits the string into chunks and builds a new string.

Solution

Intuition

This problem is a set of independent segment reversals. Each block of 2k characters depends only on its own characters, so the same rule repeats block by block. Your job is to find where each block starts and where its reversal ends.

It is like a row of cards where you flip the first k of every 2k group by swapping ends and moving inward. The buffer is the card row, the two pointers are your hands, and the untouched cards are the tail that stays put.

Reversing a range in place is the two-pointer move. Put one pointer on the left end and one on the right end, swap them, and move both inward until they meet. The String Reversal subpattern applies that move to any range, not only the whole string.

The short tails need no separate branch. Set the right end to min(i + k - 1, n - 1). If fewer than k characters remain, the min picks the last index, so the whole tail reverses. The step of 2k skips the characters that must stay unchanged.

Watch the pattern animation

Worked example

Input: s = "abcdefghij", k = 4
Output: "dcbaefghji"
Explanation: Blocks are 8 characters long. The first block is abcdefgh, and its first 4 characters reverse to dcba, so the block becomes dcbaefgh. The second block is ij. It has fewer than 4 characters, so all of it reverses to ji.

Approach 1: Brute force with block slices

A beginner splits the string into chunks and builds a new string. For each block, you slice out the first k characters and reverse that slice. Then you slice out the next k characters and keep them unchanged. You join the pieces at the end. The work is linear, because each character is sliced once. Each slice and reverse creates a new string, though. Those copies pile up in Java and Python.

Steps

  1. Create an empty list of output pieces.
  2. Set start to 0. While start is less than n, run the next two steps, then add 2k to start.
  3. Slice the first k characters of the block with s[start:start + k], and reverse that slice. Clamp the slice end to n.
  4. Slice the next k characters with s[start + k:start + 2k], and add them unchanged. An empty slice is fine when the string ends early.
  5. Join the pieces in order and return the result.

Dry run

Start with abcdefghij, k = 4. The blocks begin at 0 and 8.

Block at 0: the first 4 characters are abcd, and they reverse to dcba. The next 4 characters, efgh, go in unchanged. Pieces so far are dcba and efgh.

Block at 8: the slice ij is shorter than k, so it reverses to ji. The unchanged slice after it is empty. Joining the pieces gives dcbaefghji.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of s. The slices across all blocks cover each character once, and each character gets constant work, so the total is O(n). The pieces and the final join hold n characters, so the space is O(n). The extra allocations are a constant-factor cost that Big-O does not show.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        parts = []
        # Walk over the blocks of 2k characters
        for start in range(0, len(s), 2 * k):
            # Reverse the first k characters of the block
            parts.append(s[start:start + k][::-1])
            # Keep the next k characters as they are
            parts.append(s[start + k:start + 2 * k])
        return ''.join(parts)

The String Reversal infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

String Reversal

Part of Two Pointers

Approach 2: Two pointers on a mutable bufferOptimalString Reversal

The brute force pays for work it does not need. What's slow: every slice and reverse builds a new string, so characters get copied more than once. The insight that fixes it: a reversal is only swaps. Copy the input once into a mutable buffer, then swap inward inside each block. The tail beyond the first k characters of each block is never visited.

Why it is correct. Each swap exchanges two positions that mirror each other around the window center. When the loop ends, every position in the window holds the character that mirrored it, which is exactly a reversal. Blocks start at multiples of 2k and never overlap, so each character is handled once, and stepping by 2k leaves the next k characters unchanged as required.

Steps

  1. Copy s into a mutable character buffer. In C++, the string parameter is already a mutable copy, so use it directly.
  2. Set i to 0. While i is less than n, handle one block, then add 2k to i.
  3. Set left to i and right to min(i + k - 1, n - 1). The min clamps the window at the end of the string.
  4. While left is less than right, swap the characters at left and right, add 1 to left, and subtract 1 from right.
  5. After the loop, convert the buffer back to a string and return it.

Dry run

Start with abcdefghij, k = 4, n = 10. Each row is one step.

StepActionleftrightBuffer after step
1Start block i = 003abcdefghij
2Swap positions 0 and 312dbcaefghij
3Swap positions 1 and 221dcbaefghij
4left is not less than right, block ends21dcbaefghij
5Start block i = 8, clamp right to min(11, 9)89dcbaefghij
6Swap positions 8 and 998dcbaefghji
7Block ends, i = 16 is past n = 1098dcbaefghji

The buffer reads dcbaefghji, which is the expected output.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of s. Blocks are 2k long and the loop moves 2k at a time, so each character sits in at most one reversal window. A window of length L takes about L / 2 swaps, so all swaps together touch at most n characters. The loop runs about n / (2k) times, and the buffer holds n characters, which matches the output size.

PythonTested in our runner

from typing import List, Optional

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        # Python strings are immutable, so work on a list
        chars = list(s)
        n = len(chars)
        for i in range(0, n, 2 * k):
            left = i
            right = min(i + k - 1, n - 1)
            while left < right:
                chars[left], chars[right] = chars[right], chars[left]
                left += 1
                right -= 1
        return ''.join(chars)

Common mistakes

  • for i in range(0, n, k) steps by k instead of 2k. Every block gets reversed, including the blocks that must stay as they are. Step by 2 * k so the loop lands on the start of each block.
  • right = i + k - 1 with no clamp. On a short last block the index passes n - 1, which raises an index error in Python and Java and reads garbage in C++. Use min(i + k - 1, n - 1).
  • while left != right as the loop condition. With an even-length window the pointers step past each other and never match, so the loop never ends. Use left < right.
  • right = min(i + 2 * k - 1, n - 1), which reverses 2k characters instead of k. On abcdefg with k = 2 this gives dcbaefg, not bacdfeg.
  • s[i] = ... assignment on a Python, Java, JavaScript, Go or C# string. Those strings cannot change, so the write fails or does nothing. Copy the text into a list, char array or byte slice first.
  • Returning s after reversing a copy in Python or Java. The reversed text lives in the buffer, so join or convert the buffer and return that value.

Edge cases

  • k = 1 with s = "abcd": each block reverses one character, so the output is abcd.
  • k larger than n with s = "abc", k = 10: one block covers the whole string, so the output is cba. The loop runs once and stops.
  • Exact fit with s = "abcdefgh", k = 4: one full block of 2k characters, so the output is dcbaefgh.
  • Short last block with s = "abcde", k = 2: the blocks are abcd and e. The first becomes bacd, and the one-character tail stays e, so the output is bacde.
  • Single character with s = "a", k = 1: left equals right from the start, no swap runs, and the output is a.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Reverse String II, with how to answer them.

Unlock the follow-ups

Reverse String II FAQ

What is the time complexity of Reverse String II?

The time complexity is O(n), where n is the length of s. Each character is swapped at most once, and the block loop adds only about n / (2k) iterations of constant work.

Why use two pointers for Reverse String II?

Reversing a range is the standard two-pointer swap. Each block needs exactly that move, and clamping the right pointer with min gives the short tail the same code path.

Can Reverse String II be solved in O(1) extra space?

Only when the input is a mutable array you are allowed to change, because then the swap loop uses O(1) extra space. In Python, Java, JavaScript, Go and C#, the string is immutable, so the mutable copy takes O(n) space. That copy is the same size as the output.

Does Python slicing clamp out-of-range indexes?

Slices do clamp, so s[start:start + k] stops at the end of the string without an error. Plain indexing does not clamp, so s[i] raises an IndexError when i is past the end. The optimal solution uses indexing, so it still needs the min clamp.

Does the slicing approach have a worse Big-O than the two-pointer approach?

No. Both approaches run in O(n) time and O(n) space. The slicing version creates many temporary strings, which costs more in practice in Java and Python.

Asked at

See which companies ask this — Pro

Practise it