Skip to content
Problem 541 · LeetCode 541(opens in a new tab)

Reverse String II

EasyStrings

You are given a string s and a number k. Cut s into blocks of 2k letters, starting from the front; the last block may be shorter.

In every block, reverse the first k letters and leave the rest alone. If the last block has fewer than k letters, reverse all of it. Return the resulting string.

Example 1

Input:  s = "monkeybars", k = 3
Output: "nomkeyrabs"
Why:    blocks "monkey" and "bars"; reverse "mon" and "bar"
2 more examples and the constraints

Example 2

Input:  s = "xyz", k = 5
Output: "zyx"
Why:    fewer than k letters in total, so all of them flip

Example 3

Input:  s = "tree", k = 1
Output: "tree"
Why:    reversing one letter changes nothing

Constraints

  • 1 ≤ length of s ≤ 10,000
  • s holds only lowercase English letters
  • 1 ≤ k ≤ 10,000

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. Build from slicesO(n)
  2. Swap in place with two pointersO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10,000 lettersVerdict
Build from slicesO(n)
Clear; makes extra copies
Swap in place with two pointersO(n)
Best; one copy, swaps only

n = length of s.

Edge cases to test

  • k larger than the string. "xyz" with k = 5 reverses everything: "zyx".
  • k = 1. Every reversed part is one letter long, so the string comes back unchanged.
  • Last block between k and 2k letters. "abcde" with k = 2: blocks "abcd" and "e", giving "bacde".
  • Length exactly 2k. One full block: "abcd" with k = 2 gives "bacd".

Common mistakes

  • Moving i by k instead of 2k, which reverses every block of k.
  • Setting R to i + k − 1 without the min, which runs off the end of a short last block.
  • Reversing the second half of each block instead of the first.

How to talk through it

  1. 1Clarify. What happens to a last block shorter than k? Is s only lowercase letters?
  2. 2Give the slice version. Step by 2k, reverse the first k of each block, keep the rest. Already O(n).
  3. 3Improve the constant. Copy into a letter array once and reverse each range in place with two pointers.
  4. 4Code it. Mention the min that clamps R to the last index.
  5. 5Test out loud. Run k bigger than the string, k = 1, and a block that ends exactly at the end.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?