Problem · String
Reverse First K Characters in Every 2K Block
Learn this problemProblem statement
Given a string s and a positive integer k, process s from left to right in consecutive blocks of 2 * k characters.
- For every complete block of
2 * kcharacters, reverse its firstkcharacters and leave its nextkcharacters unchanged. - If fewer than
kcharacters remain, reverse all remaining characters. - If at least
kbut fewer than2 * kcharacters remain, reverse the firstkremaining characters and leave the rest unchanged.
Return the transformed string.
Function
reverseFirstKInEvery2KBlock(s: String, k: int) → StringExamples
Example 1
s = "abcdefgh"k = 2return = "bacdfegh"In abcd, reverse ab to obtain bacd. In efgh, reverse ef to obtain fegh. Combining the blocks gives bacdfegh.
Example 2
s = "abcdefg"k = 3return = "cbadefg"Reverse abc in the first six-character block, producing cbadef. Only g remains, so reversing the final one-character suffix leaves it unchanged.