Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Questions on Array
  • Practice Array
  • MCQs on Array
  • Tutorial on Array
  • Types of Arrays
  • Array Operations
  • Subarrays, Subsequences, Subsets
  • Reverse Array
  • Static Vs Arrays
  • Array Vs Linked List
  • Array | Range Queries
  • Advantages & Disadvantages
Open In App
Next Article:
Reverse an array upto a given position
Next article icon

Reverse an Array in groups of given size

Last Updated : 13 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

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
// C program to reverse every sub-array formed by // consecutive k elements #include <stdio.h>  // Function to reverse every sub-array formed by // consecutive k elements void reverse(int arr[], int n, int k) {     for (int i = 0; i < n; i += k)     {         int left = i;         int right;         // to handle case when k is not multiple of n         if(i+k-1<n-1)         right = i+k-1;         else         right = n-1;          // reverse the sub-array [left, right]         while (left < right)             {                 // swap                 int temp = arr[left];                 arr[left] = arr[right];                 arr[right] = temp;                 left++;                 right--;             }      } }  // Driver code int main() {     int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};     int k = 3;      int n = sizeof(arr) / sizeof(arr[0]);      reverse(arr, n, k);      for (int i = 0; i < n; i++)         printf("%d ",arr[i]);      return 0; } //  This code is contributed by Arpit Jain 
Java
import java.util.*;  class GFG {          // Function to reverse every sub-array of size k     static void reverseInGroups(int[] arr, int k) {         int n = arr.length;           for (int i = 0; i < n; i += k) {             int left = i;             int right = Math.min(i + k - 1, n - 1);               // Reverse the sub-array             while (left < right) {                 int temp = arr[left];                 arr[left] = arr[right];                 arr[right] = temp;                 left++;                 right--;             }         }     }          public static void main(String[] args) {         int[] arr = {1, 2, 3, 4, 5, 6, 7, 8};         int k = 3;          reverseInGroups(arr, k);          // Print modified array         for (int num : arr) {             System.out.print(num + " ");         }     } } 
Python
# Python 3 program to reverse every  # sub-array formed by consecutive k # elements  # Function to reverse every sub-array # formed by consecutive k elements def reverseInGroups(arr, k):     i = 0     n = len(arr)  # Get the size of the array          while i < n:         left = i           # To handle case when k is not         # multiple of n         right = min(i + k - 1, n - 1)           # Reverse the sub-array [left, right]         while left < right:             arr[left], arr[right] = arr[right], arr[left]             left += 1             right -= 1                  i += k      arr = [1, 2, 3, 4, 5, 6, 7, 8]  k = 3  reverseInGroups(arr, k)  # Print modified array print(" ".join(map(str, arr))) 
C#
// C# program to reverse every sub-array  // formed by consecutive k elements using System;  class GFG {  // Function to reverse every sub-array  // formed by consecutive k elements public static void reverse(int[] arr,                             int n, int k) {     for (int i = 0; i < n; i += k)     {         int left = i;          // to handle case when k is          // not multiple of n         int right = Math.Min(i + k - 1, n - 1);         int temp;          // reverse the sub-array [left, right]         while (left < right)         {             temp = arr[left];             arr[left] = arr[right];             arr[right] = temp;             left += 1;             right -= 1;         }     } }  // Driver Code public static void Main(string[] args) {     int[] arr = new int[] {1, 2, 3, 4,                             5, 6, 7, 8};     int k = 3;      int n = arr.Length;      reverse(arr, n, k);      for (int i = 0; i < n; i++)     {         Console.Write(arr[i] + " ");     } } } 
JavaScript
// Javascript program to reverse every sub-array // formed by consecutive k elements  // Function to reverse every sub-array // formed by consecutive k elements function reverseInGroups(arr, k) {     let n = arr.length;       for (let i = 0; i < n; i += k) {         let left = i;          // To handle case when k is not         // multiple of n         let right = Math.min(i + k - 1, n - 1);                  // Reverse the sub-array [left, right]         while (left < right) {                          // Swap elements             [arr[left], arr[right]] = [arr[right], arr[left]];             left += 1;             right -= 1;         }     }     return arr; }  // Driver Code let arr = [1, 2, 3, 4, 5, 6, 7, 8]; let k = 3; let arr1 = reverseInGroups(arr, k);  // Print modified array console.log(arr1.join(" ")); 

Output
3 2 1 6 5 4 8 7 

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



Next Article
Reverse an array upto a given position

A

Aditya Goel
Improve
Article Tags :
  • Arrays
  • DSA
Practice Tags :
  • Arrays

Similar Reads

  • Reverse an array in groups of given size | Set 3 (Single traversal)
    Given an array, reverse every sub-array formed by consecutive k elements. Examples: Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3. Output: [3, 2, 1, 6, 5, 4, 9, 8, 7, 10]Input: arr = [1, 2, 3, 4, 5, 6, 7], k = 5. Output: [5, 4, 3, 2, 1, 7, 6] Approach: We will use two pointers technique to sol
    6 min read
  • Reverse a Linked List in groups of given size
    Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Example: Input: head: 1 -> 2 -> 3 -> 4 -> 5 ->
    3 min read
  • Reverse an array in groups of given size | Set 2 (Variations of Set 1 )
    Given an array, reverse every sub-array that satisfies the given constraints.We have discussed a solution where we reverse every sub-array formed by consecutive k elements in Set 1. In this set, we will discuss various interesting variations of this problem. Variation 1 (Reverse Alternate Groups): R
    15+ min read
  • Reverse an array upto a given position
    Given an array arr[] and a position in array, k. Write a function name reverse (a[], k) such that it reverses subarray arr[0..k-1]. Extra space used should be O(1) and time complexity should be O(k). Example: Input: arr[] = {1, 2, 3, 4, 5, 6} k = 4 Output: arr[] = {4, 3, 2, 1, 5, 6} We strongly reco
    6 min read
  • Reverse a Linked List in groups of given size (Iterative Approach)
    Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -
    10 min read
  • Reverse a doubly linked list in groups of given size | Set 2
    Given a doubly-linked list containing n nodes. The problem is to reverse every group of k nodes in the list. Examples: Input: List: 10<->8<->4<->2, K=2Output: 8<->10<->2<->4 Input: List: 1<->2<->3<->4<->5<->6<->7<->8, K=3O
    15+ min read
  • Reverse a Linked List in groups of given size using Deque
    Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -
    8 min read
  • Reverse a Linked List in groups of given size using Stack
    Given a Singly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed. Examples: Input: head: 1 -> 2 -> 3 -> 4 -> 5 -
    8 min read
  • Reverse given Linked List in groups of specific given sizes
    Given the linked list and an array arr[] of size N, the task is to reverse every arr[i] nodes of the list at a time (0 ≤ i < N). Note: If the number of nodes in the list is greater than the sum of array, then the remaining nodes will remain as it is. Examples: Input: head = 1->2->3->4-
    8 min read
  • Reverse a doubly linked list in groups of K size
    Given a Doubly linked list containing n nodes. The task is to reverse every group of k nodes in the list. If the number of nodes is not a multiple of k then left-out nodes, in the end should be considered as a group and must be reversed. Examples: Input: 1 <-> 2 <-> 3 <-> 4 <-
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences