Skip to content
BytePatterns

Reverse Every K Block

EasyArrays#in-place-reversal#two-pointers~15m

Problem

Given a list and a positive integer k, reverse the order of the values inside every consecutive block of k values: the first k, then the next k, and so on. If the length is not a multiple of k, the final block is shorter than k and stays as it is. Work in place with O(1) extra space and return the same list.

Examples

Input:  nums = [1, 2, 3, 4, 5, 6, 7, 8], k = 3
Output: [3, 2, 1, 6, 5, 4, 7, 8]
Why:    two full blocks are reversed; 7 and 8 form a short block
Input:  nums = [1, 2, 3, 4], k = 4
Output: [4, 3, 2, 1]
Why:    one block covers the whole list
Input:  nums = [5, 6], k = 3
Output: [5, 6]
Why:    edge case, there is no full block at all

Hints

0 / 3

Stuck on the idea rather than the code? In-Place Reversal covers it.