DEV Community

tanzimsafin
tanzimsafin

Posted on

Reverse array in groups


Original Problem: Reverse an Array in Groups of Given Size

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)

  1. Start from index 0.
  2. Take the next k elements as a chunk: array[i : i+k].
  3. Reverse only that chunk.
  4. Jump to the next chunk by moving i forward by k.

Algorithm Steps

  • Loop through the array in steps of k:
    i = 0, k, 2k, 3k, ...

  • Reverse the current chunk:
    Replace array[i : i+k] with its reversed version.

  • Handle the edge case (last chunk smaller than k):
    If fewer than k elements 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
Enter fullscreen mode Exit fullscreen mode

Time Complexity

Total time is O(n)O(n) 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)