Reverse an array in groups of given size | Set 2 (Variations of Set 1 )
Last Updated :
23 Jul, 2025
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): Reverse every alternate sub-array formed by consecutive k elements.
Examples:
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 3
Output:
[3, 2, 1, 4, 5, 6, 9, 8, 7]
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 2
Output:
[2, 1, 3, 4, 6, 5, 7, 8]
Algorithm:
- Define a function reverse() that takes an integer array arr, its size n, and the size of the sub-arrays k as input
- Traverse the array in multiples of 2k starting from the first element, i.e., for i = 0, 2k, 4k, and so on.
- For each such i, set the left pointer to i and the right pointer to min(i + k - 1, n - 1) to handle the case when 2k is not a multiple of n.
- Reverse the sub-array [left, right] using a while loop and the swap() function.
- Repeat steps 3-4 for every alternate sub-array formed by consecutive k elements.
- In the main function, declare an integer array arr, initialize it with some values, and define the size of the sub-arrays k.
- Determine the size of the array n using the sizeof() operator.
- Call the reverse() function passing the integer array arr, its size n, and the size of the sub-arrays k as input.
- Print the modified array arr.
Below is the implementation :
C++
// C++ program to reverse every alternate sub-array
// formed by consecutive k elements
#include <iostream>
using namespace std;
// Function to reverse every alternate sub-array
// formed by consecutive k elements
void reverse(int arr[], int n, int k)
{
// increment i in multiples of 2*k
for (int i = 0; i < n; i += 2*k)
{
int left = i;
// to handle case when 2*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()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
int k = 3;
int n = sizeof(arr) / sizeof(arr[0]);
reverse(arr, n, k);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Java
// Java program to reverse
// every alternate sub-array
// formed by consecutive k elements
class GFG
{
// Function to reverse every
// alternate sub-array formed
// by consecutive k elements
static void reverse(int arr[], int n, int k)
{
// increment i in multiples of 2*k
for (int i = 0; i < n; i += 2 * k)
{
int left = i;
// to handle case when 2*k is not multiple of n
int right = Math.min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right) {
swap(arr, left++, right--);
}
}
}
static int[] swap(int[] array, int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
return array;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14};
int k = 3;
int n = arr.length;
reverse(arr, n, k);
for (int i = 0; i < n; i++)
{
System.out.print(arr[i] + " ");
}
}
}
// This code has been contributed by 29AjayKumar
Python3
# Python3 program to reverse every alternate sub-array
# formed by consecutive k elements
# Function to reverse every alternate sub-array
# formed by consecutive k elements
def reverse(arr, n, k):
# increment i in multiples of 2*k
for i in range(0,n,2*k):
left = i
# to handle case when 2*k is not multiple of n
right = min(i + k - 1, n - 1)
# 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
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
k = 3
n = len(arr)
reverse(arr, n, k)
for i in range(0,n,1):
print(arr[i],end =" ")
# This code is contributed by
# Surendra_Gangwar
C#
// C# program to reverse every alternate
// sub-array formed by consecutive k elements
using System;
class GFG
{
// Function to reverse every
// alternate sub-array formed
// by consecutive k elements
static void reverse(int []arr,
int n, int k)
{
// increment i in multiples of 2*k
for (int i = 0; i < n; i += 2 * k)
{
int left = i;
// to handle case when 2*k is
// not multiple of n
int right = Math.Min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right)
{
swap(arr, left++, right--);
}
}
}
static int[] swap(int[] array, int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
return array;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14};
int k = 3;
int n = arr.Length;
reverse(arr, n, k);
for (int i = 0; i < n; i++)
{
Console.Write(arr[i] + " ");
}
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program to reverse
// every alternate sub-array
// formed by consecutive k elements
// Function to reverse every
// alternate sub-array formed
// by consecutive k elements
function reverse(arr, n, k)
{
// Increment i in multiples of 2*k
for(let i = 0; i < n; i += 2 * k)
{
let left = i;
// To handle case when 2*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(arr, left++, right--);
}
}
}
function swap(array, i, j)
{
let temp = array[i];
array[i] = array[j];
array[j] = temp;
return array;
}
// Driver code
let arr = [ 1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14 ];
let k = 3;
let n = arr.length;
reverse(arr, n, k);
for(let i = 0; i < n; i++)
{
document.write(arr[i] + " ");
}
// This code is contributed by rag2127
</script>
Output3 2 1 4 5 6 9 8 7 10 11 12 14 13
Time Complexity: O(N)
Auxiliary Space: O(1)
Variation 2 (Reverse at given distance): Reverse every sub-array formed by consecutive k elements at given distance apart.
Examples:
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
k = 3
m = 2
Output:
[3, 2, 1, 4, 5, 8, 7, 6, 9, 10]
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
k = 3
m = 1
Output:
[3, 2, 1, 4, 7, 6, 5, 8, 10, 9]
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 2
m = 0
Output:
[2, 1, 4, 3, 6, 5, 8, 7]
Below is its implementation:
C++
// C++ program to reverse every sub-array formed by
// consecutive k elements at given distance apart
#include <iostream>
using namespace std;
// Function to reverse every sub-array formed by
// consecutive k elements at m distance apart
void reverse(int arr[], int n, int k, int m)
{
// increment i in multiples of k + m
for (int i = 0; i < n; i += k + m)
{
int left = i;
// to handle case when k + m 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()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
int k = 3;
int m = 2;
int n = sizeof(arr) / sizeof(arr[0]);
reverse(arr, n, k, m);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Java
// java program to reverse every sub-array formed by
// consecutive k elements at given distance apart
class GFG
{
// Function to reverse every sub-array formed by
// consecutive k elements at m distance apart
static void reverse(int[] arr, int n, int k, int m)
{
// increment i in multiples of k + m
for (int i = 0; i < n; i += k + m)
{
int left = i;
// to handle case when k + m is not multiple of n
int right = Math.min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right)
swap(arr,left++, right--);
}
}
static int[] swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14};
int k = 3;
int m = 2;
int n = arr.length;
reverse(arr, n, k, m );
for (int i = 0; i < n; i++)
{
System.out.print(arr[i] + " ");
}
}
}
// This code has been contributed by Rajput-Ji
Python3
# Python3 program to reverse every
# sub-array formed by consecutive
# k elements at given distance apart
# Function to reverse every
# sub-array formed by consecutive
# k elements at m distance apart
def reverse(arr, n, k, m):
# increment i in multiples of k + m
for i in range(0, n, k + m):
left = i;
# to handle case when k + m
# is not multiple of n
right = min(i + k - 1, n - 1);
# reverse the sub-array [left, right]
while (left < right):
arr = swap(arr,left, right);
left += 1;
right -= 1;
return arr;
def swap(arr, i, j):
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
# Driver code
arr = [1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14];
k = 3;
m = 2;
n = len(arr);
arr = reverse(arr, n, k, m );
for i in range(0, n):
print(arr[i], end = " ");
# This code is contributed by Rajput-Ji
C#
// C# program to reverse every sub-array
// formed by consecutive k elements at
// given distance apart
using System;
class GFG
{
// Function to reverse every sub-array
// formed by consecutive k elements
// at m distance apart
static void reverse(int[] arr, int n,
int k, int m)
{
// increment i in multiples of k + m
for (int i = 0; i < n; i += k + m)
{
int left = i;
// to handle case when k + m is
// not multiple of n
int right = Math.Min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right)
swap(arr, left++, right--);
}
}
static int[] swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14};
int k = 3;
int m = 2;
int n = arr.Length;
reverse(arr, n, k, m );
for (int i = 0; i < n; i++)
{
Console.Write(arr[i] + " ");
}
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// javascript program to reverse every sub-array formed by
// consecutive k elements at given distance apart
// Function to reverse every sub-array formed by
// consecutive k elements at m distance apart
function reverse(arr,n,k,m)
{
// increment i in multiples of k + m
for (let i = 0; i < n; i += k + m)
{
let left = i;
// to handle case when k + m is not multiple of n
let right = Math.min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right)
swap(arr,left++, right--);
}
}
function swap(arr,i,j)
{
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Driver code
let arr=[1, 2, 3, 4, 5, 6, 7, 8,
9, 10, 11, 12, 13, 14];
let k = 3;
let m = 2;
let n = arr.length;
reverse(arr, n, k, m );
for (let i = 0; i < n; i++)
{
document.write(arr[i] + " ");
}
// This code is contributed by ab2127
</script>
Output3 2 1 4 5 8 7 6 9 10 13 12 11 14
Time Complexity: O(N)
Auxiliary Space: O(1)
Variation 3 (Reverse by doubling the group size):
Reverse every sub-array formed by consecutive k elements where k doubles itself with every sub-array.
Examples:
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
k = 1
Output:
[1], [3, 2], [7, 6, 5, 4], [15, 14, 13, 12, 11, 10, 9, 8]
Below is its implementation:
C++
// C++ program to reverse every sub-array formed by
// consecutive k elements where k doubles itself with
// every sub-array.
#include <iostream>
using namespace std;
// Function to reverse every sub-array formed by
// consecutive k elements where k doubles itself
// with every sub-array.
void reverse(int arr[], int n, int k)
{
// increment i in multiples of k where value
// of k is doubled with each iteration
for (int i = 0; i < n; i += k/2)
{
int left = i;
// to handle case when number of elements in
// last group is less than k
int right = min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right)
swap(arr[left++], arr[right--]);
// double value of k with each iteration
k = k*2;
}
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int k = 1;
int n = sizeof(arr) / sizeof(arr[0]);
reverse(arr, n, k);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Java
// Java program to reverse every sub-array
// formed by consecutive k elements where
// k doubles itself with every sub-array.
import java.util.*;
class GFG
{
// Function to reverse every sub-array formed by
// consecutive k elements where k doubles itself
// with every sub-array.
static void reverse(int arr[], int n, int k)
{
// increment i in multiples of k where value
// of k is doubled with each iteration
for (int i = 0; i < n; i += k / 2)
{
int left = i;
// to handle case when number of elements in
// last group is less than k
int right = Math.min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right)
swap(arr, left++, right--);
// double value of k with each iteration
k = k * 2;
}
}
static int[] swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Driver code
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16};
int k = 1;
int n = arr.length;
reverse(arr, n, k);
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program to reverse every
# sub-array formed by consecutive
# k elements where k doubles itself
# with every sub-array
# Function to reverse every sub-array
# formed by consecutive k elements
# where k doubles itself with every
# sub-array
def reverse(arr, n, k):
i = 0
# Increment i in multiples of k where
# value of k is doubled with each
# iteration
while (i < n):
left = i
# To handle case when number of elements
# in last group is less than k
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
# Double value of k with each iteration
k = k * 2
i += int(k / 2)
# Driver code
arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16]
k = 1
n = len(arr)
reverse(arr, n, k)
print(*arr, sep = ' ')
# This code is contributed by avanitrachhadiya2155
C#
// C# program to reverse every sub-array
// formed by consecutive k elements where
// k doubles itself with every sub-array.
using System;
class GFG
{
// Function to reverse every sub-array formed by
// consecutive k elements where k doubles itself
// with every sub-array.
static void reverse(int []arr, int n, int k)
{
// increment i in multiples of k where value
// of k is doubled with each iteration
for (int i = 0; i < n; i += k / 2)
{
int left = i;
// to handle case when number of elements in
// last group is less than k
int right = Math.Min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right)
swap(arr, left++, right--);
// double value of k with each iteration
k = k * 2;
}
}
static int[] swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Driver code
public static void Main(String[] args)
{
int []arr = {1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16};
int k = 1;
int n = arr.Length;
reverse(arr, n, k);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Rajput-Ji
JavaScript
<script>
// Javascript program to reverse every sub-array
// formed by consecutive k elements where
// k doubles itself with every sub-array.
// Function to reverse every sub-array formed by
// consecutive k elements where k doubles itself
// with every sub-array.
function reverse(arr,n,k)
{
// increment i in multiples of k where value
// of k is doubled with each iteration
for (let i = 0; i < n; i += k / 2)
{
let left = i;
// to handle case when number of elements in
// last group is less than k
let right = Math.min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while (left < right)
swap(arr, left++, right--);
// double value of k with each iteration
k = k * 2;
}
}
function swap(arr,i,j)
{
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
return arr;
}
// Driver code
let arr=[1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16];
let k = 1;
let n = arr.length;
reverse(arr, n, k);
document.write(arr.join(" "));
// This code is contributed by unknown2108
</script>
Output1 3 2 7 6 5 4 15 14 13 12 11 10 9 8 16
Time complexity of all solutions discussed above is O(n).
Auxiliary space used by the program is O(1).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem