Open In App

Reverse an Array in groups of given size

Last Updated : 20 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Given an array arr[] and an integer k, the task is to reverse every subarray formed by consecutive K elements.

Examples: 

Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8, 9], k = 3 
Output: 3, 2, 1, 6, 5, 4, 9, 8, 7

Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8], k = 5 
Output: 5, 4, 3, 2, 1, 8, 7, 6

Input: arr[] = [1, 2, 3, 4, 5, 6], k = 1 
Output: 1, 2, 3, 4, 5, 6

Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8], k = 10 
Output: 8, 7, 6, 5, 4, 3, 2, 1

Approach:

 The problem can be solved based on the following idea:

Consider every sub-array of size k starting from the beginning of the array and reverse it. We need to handle some special cases. 

  • If k is not a multiple of n where n is the size of the array, for the last group we will have less than k elements left, we need to reverse all remaining elements. 
  • If k = 1, the array should remain unchanged. If k >= n, we reverse all elements present in the array.

To reverse a subarray, maintain two pointers: left and right. Now, swap the elements at left and right pointers and increment left by 1 and decrement right by 1. Repeat till left and right pointers don’t cross each other.

Working:

C++
#include <iostream>
#include <vector>
using namespace std;

// Function to reverse every sub-array formed by
// consecutive k elements
void reverseInGroups(vector<int>& arr, int k) {
    int n = arr.size();  // Get the size of the array

    for (int i = 0; i < n; i += k)
    {
        int left = i;

        // to handle case when k is not multiple of n
        int right = min(i + k - 1, n - 1);

        // reverse the sub-array [left, right]
        while (left < right)
            swap(arr[left++], arr[right--]);

    }
}

// Driver code
int main()
{
    vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8}; // Input array
    int k = 3; // Size of sub-arrays to be reversed

    reverseInGroups(arr, k); // Call function to reverse in groups

    // Print modified array
    for (int num : arr)
        cout << num << " ";

    return 0;
}
C Java Python C# JavaScript

Output
3 2 1 6 5 4 8 7 

Time complexity: O(n)
Auxiliary space: O(1)







Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg