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.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code