701191. Reverse array in groups

Basic

Reverse array in groups0255

Summary

Reverse an array in groups, where each group contains a specified number of elements. This problem requires us to understand how arrays work and how we can manipulate them efficiently.

Detailed Explanation

Given an integer n, representing the size of the array, and another integer k, representing the size of each group, our task is to reverse every group in the array. For example, if we have an array [1, 2, 3, 4, 5, 6, 7] with n = 7 and k = 3, the output should be [3, 2, 1, 7, 6, 5, 4].

To solve this problem, we can iterate through the array in groups. For each group, we reverse the elements before moving on to the next group. This approach ensures that every group is reversed correctly.

Here's a step-by-step breakdown of the solution:

  1. Initialize two pointers, start and end, to represent the current group.
  2. Iterate through the array until end exceeds the length of the array or the end of the current group is reached.
  3. During each iteration, if the current element belongs to the current group (i.e., its index is a multiple of k), reverse the elements between start and end.
  4. Update start and end for the next group.
  5. Repeat steps 2-4 until the end of the array is reached.

The time complexity of this solution is O(n), where n is the size of the array, since we're iterating through the array once. The space complexity is O(1) because we're not using any additional space that scales with the input size.

Optimized Solutions

Java

View on GeeksforGeeks
public void reverseArrayInGroups(int[] arr, int k) {
    for (int i = 0; i < arr.length; i += k) {
        int start = Math.min(i, arr.length - 1);
        int end = Math.min(start + k - 1, arr.length - 1);
        int left = start;
        int right = end;
        while (left < right) {
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.