Reverse array in groups
Source: Dev.to
Problem Statement
Reverse an array in groups of a given size k.
The array is divided into consecutive chunks (windows) of length k, and each chunk is reversed independently. The last chunk may contain fewer than k elements; it should also be reversed.
Approach
- Iterate over the array in steps of
k(indices0, k, 2k, …). - For each starting index
i, reverse the sub‑arrayarr[i : i+k]. - Continue until the end of the array is reached.
The slice operation automatically handles the edge case where the remaining elements are fewer than k.
Implementation (Python)
def reverse_in_groups(arr, k):
"""
Reverse the elements of `arr` in groups of size `k`.
Parameters
----------
arr : list
The list to be processed.
k : int
The size of each group.
Returns
-------
list
The list with each group reversed.
"""
n = len(arr)
for i in range(0, n, k):
# Reverse the sub-array from i to i+k
arr[i:i + k] = reversed(arr[i:i + k])
return arr
Complexity
- Time:
O(n)– each element is visited at most twice (once during iteration and once during reversal). - Space:
O(1)additional space (the reversal is done in‑place).
Example
arr = [1, 2, 4, 5, 7]
k = 3
- Chunk 1:
[1, 2, 4] → [4, 2, 1] - Chunk 2 (edge case):
[5, 7] → [7, 5]
Result: [4, 2, 1, 7, 5]