Reverse String II - 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.

Rules:

  • 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, then reverse the first k characters and leave the other as original.

Return the modified string.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcdefg", k = 2
Output: "bacdfeg"
💡 Note: First 2k=4 chars: reverse "ab" → "ba", keep "cd". Next chunk: reverse "ef" → "fe", keep "g". Result: "bacdfeg"
Example 2 — Exact Multiple
$ Input: s = "abcd", k = 2
Output: "bacd"
💡 Note: String length equals 2k=4. Reverse first k=2 characters "ab" → "ba", keep remaining "cd". Result: "bacd"
Example 3 — Short String
$ Input: s = "a", k = 2
Output: "a"
💡 Note: String length (1) is less than k=2, so reverse all characters. Single character "a" reversed is still "a"

Constraints

  • 1 ≤ s.length ≤ 104
  • s consists of only lowercase English letters
  • 1 ≤ k ≤ 104

Visualization

Tap to expand
Reverse String II: s = "abcdefg", k = 2Input String:abcdefg2k = 4 charsRemainingAfter Processing:bacdfegReversedUnchangedReversedUnchangedOutput: "bacdfeg"
Understanding the Visualization
1
Input
String s and integer k define the reversal pattern
2
Process
Divide into 2k chunks, reverse first k of each
3
Output
Modified string with selective reversals
Key Takeaway
🎯 Key Insight: Process string in 2k chunks, applying two pointers reversal only to the first k characters of each chunk
Asked in
Google 25 Amazon 30 Facebook 15 Apple 10
28.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen