Problem 268753 · medium · Phase 02 Linear Data Structures

Reverse in Groups of K

arrays · slicing · reversal

Given a list nums and a positive integer k, return a new list in which every consecutive block of k elements is reversed. The blocks themselves stay in order. If the final block has fewer than k elements, it is reversed as well.

Examples

Input:  nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [3, 2, 1, 6, 5, 4, 7]
Explanation: blocks [1,2,3], [4,5,6] and [7] are each reversed.

Input:  nums = [1, 2, 3], k = 5
Output: [3, 2, 1]

Constraints

  • 0 <= len(nums) <= 10**5
  • 1 <= k <= 10**5
  • Return a new list; do not modify nums.
  • Target: O(n) time.

Goals

  • Process a list block by block
  • Reverse a shorter trailing block the same way
  • Keep the blocks in their original order
Starting Python…