The Wayback Machine - https://web.archive.org/web/20240815201101/https://www.geeksforgeeks.org/reverse-an-array-in-groups-of-given-size/
Open In App

Reverse an Array in groups of given size

Last Updated : 08 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
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.

Below is the implementation of the above approach:

C++
// C++ program to reverse every sub-array formed by
// consecutive k elements
#include <iostream>
using namespace std;

// 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;

        // 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()
{
    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++)
        cout << arr[i] << " ";

    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
// Java program to reverse every sub-array formed by
// consecutive k elements
class GFG {
    
    // Function to reverse every sub-array formed by
    // consecutive k elements
    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 method
    public static void main(String[] args)
    {
        
        int arr[] = {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++)
            System.out.print(arr[i] + " ");
    }
}

// This code is contributed by Anant Agarwal.
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 reverse(arr, n, k):
    i = 0
    
    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
    
# Driver code
arr = [1, 2, 3, 4, 5, 6,
                   7, 8] 

k = 3
n = len(arr) 
reverse(arr, n, k)

for i in range(0, n):
        print(arr[i], end =" ")
        
# This code is contributed by Smitha Dinesh Semwal
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] + " ");
    }
}
}

// This code is contributed 
// by Shrikant13
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 reverse(arr, n, k)
{
    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);
        let temp;
        
        // Reverse the sub-array [left, right]
        while (left < right)
        {
            temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left += 1;
            right -= 1;
        }
    }
    return arr;
}

// Driver Code
let arr = new Array(1, 2, 3, 4, 5, 6, 7, 8);
let k = 3;
let n = arr.length;
let arr1 = reverse(arr, n, k);

for(let i = 0; i < n; i++)
    console.log(arr1[i] + " ");
PHP
<?php
// PHP program to reverse every sub-array 
// formed by consecutive k elements
    
// Function to reverse every sub-array 
// formed by consecutive k elements
function reverse($arr, $n, $k)
{
    for ($i = 0; $i < $n; $i += $k)
    {
        $left = $i;

        // to handle case when k is not 
        // multiple of n
        $right = min($i + $k - 1, $n - 1);
        $temp;
        
        // reverse the sub-array [left, right]
        while ($left < $right)
        {
            $temp = $arr[$left];
            $arr[$left] = $arr[$right];
            $arr[$right] = $temp;
            $left += 1;
            $right -= 1;
        }
    }
    return $arr;
}

// Driver Code
$arr = array(1, 2, 3, 4, 5, 6, 7, 8);
$k = 3;

$n = sizeof($arr);

$arr1 = reverse($arr, $n, $k);

for ($i = 0; $i < $n; $i++)
    echo $arr1[$i] . " ";

// This code is contributed 
// by Akanksha Rai
?>

Output
3 2 1 6 5 4 8 7 

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

Working:




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 solve this problem.First, we will initialize our 1st
6 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): Reverse every alternate sub-array formed by consecu
15+ min read
Reverse a doubly linked list in groups of given size
Given a doubly linked list containing n nodes. The problem is to reverse every group of k nodes in the list. Examples: Prerequisite: Reverse a doubly linked list | Set-2. Approach: Create a recursive function say reverse(head, k). This function receives the head or the first node of each group of k nodes. It reverses those groups of k nodes by appl
15+ min read
Reverse a Linked List in groups of given size (Iterative Approach)
Given a linked list and an integer K, the task is to reverse every K nodes of the given linked list. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 8 -&gt; NULL, K = 3 Output: 3 2 1 6 5 4 8 7 Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 8 -&gt; NULL, K = 5 Output: 5 4 3 2 1 8 7 6 Approach: We have already
12 min read
Reverse a singly Linked List in groups of given size | Set 3
Given a singly linked list and an integer K, the task is to reverse every K nodes of the given linked list. Examples: Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 8 -&gt; NULL, K = 3 Output: 3 2 1 6 5 4 8 7 Input: 1 -&gt; 2 -&gt; 3 -&gt; 4 -&gt; 5 -&gt; 6 -&gt; 7 -&gt; 8 -&gt; NULL, K = 5 Output: 5 4 3 2 1 8 7 6 Approach: Two diff
11 min read
Reverse a singly Linked List in groups of given size | Set 4 (Space efficient approach)
Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples: Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL, k = 3Output: 3-&gt;2-&gt;1-&gt;6-&gt;5-&gt;4-&gt;8-&gt;7-&gt;NULL Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL, k = 5Output: 5-&gt;4-&gt;3-&gt;2-&gt;1-&gt;8-&gt;
9 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&lt;-&gt;8&lt;-&gt;4&lt;-&gt;2, K=2Output: 8&lt;-&gt;10&lt;-&gt;2&lt;-&gt;4 Input: List: 1&lt;-&gt;2&lt;-&gt;3&lt;-&gt;4&lt;-&gt;5&lt;-&gt;6&lt;-&gt;7&lt;-&gt;8, K=3Output: 3&lt;-&gt;2&lt;-&gt;1&lt;-&gt;6&lt;-&gt;5
15+ min read
Reverse a Linked List in groups of given size
Given a linked list, write a function to reverse every k nodes (where k is an input to the function). Example: Input: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL, K = 3 Output: 3-&gt;2-&gt;1-&gt;6-&gt;5-&gt;4-&gt;8-&gt;7-&gt;NULL Input: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL, K = 5 Output: 5-&gt;4-&gt;3-&gt;2-&gt;1-&gt;8-&gt;
15+ min read
Reverse a Linked List in groups of given size using Stack
Given a linked list, write a function to reverse every k node (where k is an input to the function). Examples: Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL and k = 3 Output: 3-&gt;2-&gt;1-&gt;6-&gt;5-&gt;4-&gt;8-&gt;7-&gt;NULL. Inputs: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL and k = 5 Output: 5-&gt;4-&gt;3-&gt;2-&gt;1-
10 min read
XOR Linked List - Reverse a Linked List in groups of given size
Given a XOR linked list and an integer K, the task is to reverse every K nodes in the given XOR linked list. Examples: Input: XLL = 7&lt; – &gt; 6 &lt; – &gt; 8 &lt; – &gt; 11 &lt; – &gt; 3, K = 3 Output: 8 &lt; – &gt; 6 &lt; – &gt; 7 &lt; – &gt; 3 &lt; – &gt; 11 Explanation: Reversing first K(= 3) nodes modifies the Linked List to 8 &lt; – &gt; 6
13 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 &lt; 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-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;9, arr[] = {2, 3, 3}Outp
8 min read
Number of ways of distributing N identical objects in R distinct groups with no groups empty
Given two integer N and R, the task is to calculate the number of ways to distribute N identical objects into R distinct groups such that no groups are left empty. Examples: Input: N = 4, R = 2 Output: 3 No of objects in 1st group = 1, in second group = 3 No of objects in 1st group = 2, in second group = 2 No of objects in 1st group = 3, in second
5 min read
Divide Matrix into K groups of adjacent cells having minimum difference between maximum and minimum sized groups
Given N rows and M columns of a matrix, the task is to fill the matrix cells using first K integers such that: Each group of cells is denoted by a single integer.The difference between the group containing the maximum and the minimum number of cells should be minimum.All the cells of the same group should be contiguous i.e., for any group, two adja
11 min read
Javascript Program For Reversing A Linked List In Groups Of Given Size - Set 1
Given a linked list, write a function to reverse every k nodes (where k is an input to the function).  Example:  Input: 1->2->3->4->5->6->7->8->NULL, K = 3 Output: 3->2->1->6->5->4->8->7->NULL Input: 1->2->3->4->5->6->7->8->NULL, K = 5 Output: 5->4->3->2->1->8->7->6->NULL  Recommended: Please solve it on "PRACTICE" first, before moving on to the so
3 min read
Javascript Program For Reversing A Linked List In Groups Of Given Size- Set 2
Given a linked list, write a function to reverse every k nodes (where k is an input to the function). Examples: Input: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL and k = 3 Output: 3-&gt;2-&gt;1-&gt;6-&gt;5-&gt;4-&gt;8-&gt;7-&gt;NULL. Input: 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6-&gt;7-&gt;8-&gt;NULL and k = 5 Output: 5-&gt;4-&gt;3-&gt;2-&gt;1-
3 min read
Find array using different XORs of elements in groups of size 4
Given an array q[] of XOR queries of size N (N is a multiple of 4) which describe an array of the same size as follows: q[0 - 3] describe arr[0 - 3], q[4 - 7] describe arr[4 - 7], and so on... If arr[0 - 3] = {a1, a2, a3, a4} then q[0 - 3] = {a1 ? a2 ? a3, a1 ? a2 ? a4, a1 ? a3 ? a4, a2 ? a3 ? a4} The task is to find the values of the original arra
7 min read
Check if Array can be divided into K groups of size C and all elements of group are distinct
Given an array A[] of size N, and two integers K and C, the task is to check if all the elements of the array can be grouped into K groups such that each group has at most C elements and all the elements of a group are distinct. Examples: Input: N=6, A=[1, 2, 1, 2, 3, 4], K = 2, C=3Output: PossibleExplanation: Let 2 groups be k1, k2 of capacity 3.I
10 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 min read
Minimum difference between groups of size two
Given an array of even number of elements, form groups of 2 using these array elements such that the difference between the group with the highest sum and the one with the lowest sum is minimum. Note: An element can be a part of one group only and it has to be a part of at least 1 group. Examples: Input : arr[] = {2, 6, 4, 3} Output : 1 Groups form
8 min read
Maximum difference between groups of size two
Given an array of even number of elements, form groups of 2 using these array elements such that the difference between the group with highest sum and the one with lowest sum is maximum. Note: An element can be a part of one group only and it has to be a part of at least 1 group. Examples: Input : arr[] = {1, 4, 9, 6} Output : 10 Groups formed will
9 min read
Number of ways to make binary string of length N such that 0s always occur together in groups of size K
Given two integers N and K, the task is to count the number of ways to make a binary string of length N such that 0s always occur together in a group of size K.Examples: Input: N = 3, K = 2 Output : 3 No of binary strings: 111 100 001Input : N = 4, K = 2 Output : 5 Recommended: Please try your approach on {IDE} first, before moving on to the soluti
9 min read
Count of groups having largest size while grouping according to sum of its digits
Given an integer N, the task is to find the number of groups having the largest size. Each number from 1 to N is grouped according to the sum of its digits. Examples: Input: N = 13 Output: 4 Explanation: There are 9 groups in total, they are grouped according to the sum of its digits of numbers from 1 to 13: [1, 10] [2, 11] [3, 12] [4, 13] [5] [6]
7 min read
Maximize number of groups formed with size not smaller than its largest element
Given an array arr[] of N positive integers(1 ? arr[i] ? N ), divide the elements of the array into groups such that the size of each group is greater than or equal to the largest element of that group. It may be also possible that an element cannot join any group. The task is to maximize the number of groups. Examples: Input: arr = {2, 3, 1, 2, 2}
7 min read
Maximum number of groups that can receive fresh donuts distributed in batches of size K
Given an array arr[] consisting of N positive integers such that arr[i] denotes the size of the ith group sitting in a donut shop and a positive integer K, which denotes the maximum number of donuts that can be served in a batch, the task is to find the maximum number of groups that can receive fresh donuts if the customers of the same group are se
15+ min read
Javascript Program for Maximum difference between groups of size two
Given an array of even number of elements, form groups of 2 using these array elements such that the difference between the group with highest sum and the one with lowest sum is maximum.Note: An element can be a part of one group only and it has to be a part of at least 1 group. Examples: Input : arr[] = {1, 4, 9, 6} Output : 10 Groups formed will
3 min read
Maximize groups to be formed such that product of size of group with its minimum element is at least K
Given an array, arr[] of length N, and an integer K. The value of the i-th element is arr[i]. The task is to find the maximum number of groups such that for each group the product of the number of elements in that group and the minimum element is at least K. Note: Every element should belong to exactly one group and some elements may not be part of
8 min read
Check whether N items can be divided into K groups of unique size
Given integers N and K, the task is to check if it is possible to divide N numbers into K groups such that all the K groups are of different size and each part has at least one number. Examples: Input: N = 5, K = 2Output: YesExplanation: 5 numbers can be divided into 2 parts of different size. The possible size of the groups can be (1, 4) and (2, 3
8 min read
Find the size of largest group where groups are according to the xor of digits
Given an integer N and the task is to find the size of the largest group in a range 1 to N, where two numbers belong to the same group if xor of its digits is the same. Examples: Input: N = 13 Output: 2 Explanation: There are 10 groups in total, they are grouped according to the xor of its digits of numbers from 1 to 13: [11] [1, 10] [2, 13] [3, 12
14 min read
Count all possible groups of size 2 or 3 that have sum as multiple of 3
Given an unsorted integer (positive values only) array of size ‘n’, we can form a group of two or three, the group should be such that the sum of all elements in that group is a multiple of 3. Count all possible number of groups that can be generated in this way. Examples: Input: arr[] = {3, 6, 7, 2, 9} Output: 8 // Groups are {3,6}, {3,9}, {9,6},
13 min read
Maximum number of groups of size 3 containing two type of items
Given n instance of item A and m instance of item B. Find the maximum number of groups of size 3 that can be formed using these items such that all groups contain items of both types, i.e., a group should not have either all items of type A or all items of type B. The total number of items of type A in the formed groups must be less than or equal t
10 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg