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 fewer than k characters are left, reverse all of them. If at least k but fewer than 2k characters are left, reverse the first k and leave the rest as they are.

30:00

Reverse String II
easy
Free written solution
Topics
Companies

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, reverse all of them. If at least k but fewer than 2k characters are left, reverse the first k and leave the rest as they are.

Example 1:
Input: {"s":"abcdefg","k":2}
Output: bacdfeg
Constraints:
  • 1≤s.length≤1041 \leq s.\text{length} \leq 10^4

  • s consists of only lowercase English letters.

  • 1≤k≤1041 \leq k \leq 10^4

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"abcdefg","k":2}

Split "abcdefg" into blocks of 2k = 4. In each block, reverse the first k = 2 characters and leave the next 2 alone.

first k: reverse
next k: keep
k = 2, block = 4
a
0
b
1
c
2
d
3
e
4
f
5
g
6

current block

-

blocks done

0 / 2

Variables
VariableValue
k2
start-1
left-1
right-1
DepthFunction Call
Stack empty
0/7