Reverse array in groups


Tue Feb 08 2022 06:17:15 GMT+0000 (UTC)

Saved by @Uttam #java #gfg #geeksforgeeks #arrays #practice #reversearray

class Solution{
    //Function to reverse any part of the array.
    void reverse(ArrayList<Integer> arr, int n,int left, int right)
           //reversing the sub-array from left index to right index.
            while (left < right) { 
                //swapping values at index stored at left and right index.
                int temp = arr.get(left); 
                arr.set(left, arr.get(right)); 
                arr.set(right, temp);
                //updating values of left and right index.
    //Function to reverse every sub-array group of size k.
    void reverseInGroups(ArrayList<Integer> arr, int n, int k) {
        for (int i = 0; i < n; i += k) { 
            //If (ith index +k) is less than total number of elements it means
            //k elements exist from current index so we reverse k elements 
            //starting from current index.
            if(i+k < n){ 
                //reverse function called to reverse any part of the array.
            //Else k elements from current index doesn't exist. 
            //In that case we just reverse the remaining elements.
                //reverse function called to reverse any part of the array.

Reverse array in groups Given an array arr[] of positive integers of size N. Reverse every sub-array group of size K. Example 1: Input: N = 5, K = 3 arr[] = {1,2,3,4,5} Output: 3 2 1 5 4 Explanation: First group consists of elements 1, 2, 3. Second group consists of 4,5. Example 2: Input: N = 4, K = 3 arr[] = {5,6,8,9} Output: 8 6 5 9 Your Task: You don't need to read input or print anything. The task is to complete the function reverseInGroups() which takes the array, N and K as input parameters and modifies the array in-place. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ N, K ≤ 10^7 1 ≤ A[i] ≤ 10^18