Reverse String II
The key idea
Walk the string in strides of
2k. At every stride, unconditionally reverse just the first k characters of that window and leave the next k untouched. Python slicing handles the short tail automatically: s[i:i+k] clips when fewer than k characters remain.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.
If there are fewer than k characters left, reverse all of them. If there are at least k but fewer than 2k characters, then reverse the first k characters and leave the rest as they are.
Constraints
- 1 <=
s.length<= 10^4 sconsists of only lowercase English letters.- 1 <=
k<= 10^4
Examples
Input: s = "abcdefg", k = 2
Output: "bacdfeg"
Input: s = "abcd", k = 2
Output: "bacd"
Complexity
Time: O(n) Space: O(n)
See the full solution
- ✓Full worked approach
- ✓Reference code in 5 languages
- ✓Problem-solving tips
- ✓Step-by-step animated visualization