67. Flip Every Other Chunk

A text is cut into consecutive chunks of 2k characters, the last chunk possibly shorter. In every chunk you must reverse only the first k characters and leave the rest of the chunk alone. If a chunk has fewer than k characters, reverse all of them. If it has at least k but fewer than 2k characters, reverse just the first k.

Given the string s and the integer k, return the edited string.

Example 1

Input:
s = "abcdefgh", k = 3
Output:
"cbadefhg"
Explanation:

The first chunk abcdef becomes cbadef, and the short tail gh is reversed to hg, giving cbadefhg.

Example 2

Input:
s = "abcdefghij", k = 4
Output:
"dcbaefghji"
Explanation:

The first chunk abcdefgh becomes dcbaefgh, and the tail ij is reversed to ji, giving dcbaefghji.

Constraints

1 ≤ s.length ≤ 105

1 ≤ k ≤ 104

s contains only lowercase English letters

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…