VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-an-array-in-groups-of-given-size/

⇱ Reverse an Array in groups - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse an Array in groups

Last Updated : 28 Mar, 2026

Given an array arr[] and an integer k, find the array after reversing every subarray of consecutive k elements in place. If the last subarray has fewer than k elements, reverse it as it is. Modify the array in place, do not return anything.

Examples:

Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8], k = 3
Output: [3, 2, 1, 6, 5, 4, 8, 7]
Explanation: Elements is reversed: [1, 2, 3] → [3, 2, 1], [4, 5, 6] → [6, 5, 4], and the last group [7, 8](size < 3) is reversed as [8, 7].

Input: arr[] = [1, 2, 3, 4, 5], k = 3
Output: [3, 2, 1, 5, 4]
Explanation: First group consists of elements 1, 2, 3. Second group consists of 4, 5.

Input: arr[] = [5, 6, 8, 9], k = 5
Output: [9, 8, 6, 5]
Explanation: Since k is greater than array size, the entire array is reversed.

Fixed-Size Group Reversal–Time O(n) and Space O(1)

Edge Cases:

  • When k = 1, the array stays the same
  • When k is greater than or equal to the array size

Approach

  • We begin from index 0 and find the size of the current subarray to be reversed. If the number of remaining elements at the end is less than k, reverse all of them.
  • Each subarray is reversed using two pointers that start from the two corners of the subarray.

Output
3 2 1 6 5 4 8 7 
Comment
Article Tags:
Article Tags: