dsa · easy
Reverse String II
Given lowercase string s and a positive integer k, process s in windows of length 2k from the left:
- in each full window, reverse the first
kcharacters and leave the nextkcharacters as they are - if the leftover tail has fewer than
kcharacters, reverse the whole tail - if the leftover tail has at least
kbut fewer than2kcharacters, reverse the firstkof the tail and leave the rest
Return the resulting string.
Example
s = "abcdefgh", k = 3. Windows are length 2k = 6, so the split is "abcdef" plus tail "gh".
In "abcdef" reverse the first 3: "cba" + "def". The tail "gh" has length 2, which is less than k, so reverse all of it: "hg".
Result: "cbadefhg".
s = "abcd", k = 2: one window of length 4. Reverse the first 2, leave the last 2 → "bacd".
## Arguments - s — lowercase string to rewrite - k — window half-width; reverse the first k of every 2k characters
Constraints
1 <= s.length <= 4*10^4 s consists of lowercase English letters 1 <= k <= 10^4 Hidden tests include near-max size for this bound; a slower-than-intended solution TLEs.
Examples
Example 1
Input: "abcdefgh" 3 Expected: cbadefhg
Example 2
Input: "abcd" 2 Expected: bacd
Example 3
Input: "abcdefg" 2 Expected: bacdfeg