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
kcharacters left, reverse all of them. - If there are less than
2kbut greater than or equal tokcharacters, then reverse the firstkcharacters 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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code