Reverse String II

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, reverse the first k characters and leave the other characters as original.
Example 1
Inputs = "abcdefg", k = 2
Output"bacdfeg"
For every 2k = 4 characters, the first 2 characters are reversed, producing "bacdfeg".
Example 2
Inputs = "abcd", k = 2
Output"bacd"
The first 2 characters are reversed and the remaining characters are left unchanged.

Constraints

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

Asked at 7 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate