Using Chunking Technique (Reversal)
We want to reverse an array in groups of size k. Think of the array as being split into consecutive chunks (windows) of length k, and we reverse each chunk one by one.
Key Idea (Chunk-by-Chunk)
- Start from index
0. - Take the next
kelements as a chunk:array[i : i+k]. - Reverse only that chunk.
- Jump to the next chunk by moving
iforward byk.
Algorithm Steps
Loop through the array in steps of
k:
i = 0, k, 2k, 3k, ...Reverse the current chunk:
Replacearray[i : i+k]with its reversed version.Handle the edge case (last chunk smaller than
k):
If fewer thankelements remain,array[i : i+k]simply returns the remaining elements.
Reversing it still works, so no extra checks are needed.
Implementation
def reverse_in_groups(arr, k):
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
Time Complexity
Total time is because each element is visited at most twice (once during iteration and once during reversal).
Example Walkthrough
Array: [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]
Top comments (0)