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.

Input & Output

Example 1 — Basic Case
$ Input: s = "abcdef", k = 2
Output: "bacdfe"
💡 Note: First 2k=4 chars "abcd": reverse first k=2 to get "bacd". Last 2 chars "ef": reverse both to get "fe". Result: "bacdfe"
Example 2 — Exact Multiple
$ Input: s = "abcd", k = 2
Output: "bacd"
💡 Note: String length equals 2k=4. Reverse first k=2 chars "ab" to "ba", keep "cd" as-is. Result: "bacd"
Example 3 — Single Character
$ Input: s = "a", k = 1
Output: "a"
💡 Note: Less than k characters remaining, so reverse all of them. 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
INPUTALGORITHMRESULTs = "abcdef", k = 2abcdefChunk 1Chunk 2Every 2k=4 chars1Process ChunksDivide string into 2k segments2Reverse First kReverse first k chars of each chunk3Keep RemainingLeave other chars unchanged4Combine ResultJoin all processed segmentsbacdfe"bacdfe"ab→ba, cd→cd, ef→feKey Insight:Process string in chunks of 2k characters, reversing only the first kcharacters of each chunk while keeping the rest unchanged.TutorialsPoint - Reverse String II | Two Pointers Approach
Asked in
Google 25 Facebook 18 Amazon 15
28.4K 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