Title: Reverse an Array in Groups of K
Reversing an array in groups of K is a classic interview question that tests two habits at once, careful index arithmetic and clean handling of a partial last group. In this guide, you’ll learn a straightforward in-place approach, walk through a complete Java program, trace it on a small input, and work through the edge cases that interviewers specifically probe for.
Understanding the Problem
Given an integer array arr and a positive integer k, we need to reverse every contiguous block of k elements starting from index 0. If the final block has fewer than k elements, we still reverse whatever is left. The order of the groups themselves does not change, only the order inside each group.
For example, with arr = {1, 2, 3, 4, 5, 6, 7, 8} and k = 3, the three groups are {1, 2, 3}, {4, 5, 6}, and the partial group {7, 8}. After reversing each group we get:
Input : {1, 2, 3, 4, 5, 6, 7, 8}, k = 3
Output: {3, 2, 1, 6, 5, 4, 8, 7}Approach
The cleanest approach is in place with two pointers. We iterate over the array in steps of k, and for each group we point left at the first element and right at the last element of that group, clamped to the end of the array for the partial final group. We then swap inward until the pointers meet.
- Let
nbe the length ofarr. Start an outer loop withi = 0and advanceibykon each iteration whilei < n. - Set
left = ias the first index of the current group. - Set
right = Math.min(i + k - 1, n - 1)so the last partial group is handled safely. - While
left < right, swaparr[left]witharr[right]. - After each swap, do
left++andright--to move the pointers inward. - When the outer loop ends, every group has been reversed inside the original array.
Java Program
Here is the complete, compilable program. The method reverseInGroups mutates the input array directly, which keeps the extra memory at O(1).
import java.util.Arrays;
public class ReverseArrayInGroups {
public static void reverseInGroups(int[] arr, int k) {
if (arr == null || k <= 1) {
return;
}
int n = arr.length;
for (int i = 0; i < n; i += k) {
int left = i;
int right = Math.min(i + k - 1, n - 1);
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);
System.out.println("Reversed Array: " + Arrays.toString(arr));
}
}Explanation of the Program
- The guard at the top returns early when
arrisnullor whenkis0or1, since neither case can produce a meaningful reversal. - The outer
forloop walks the array in jumps ofk, soiis always the first index of the group currently being reversed. - Inside each iteration,
leftstarts at the group’s first index andrightis clamped byMath.min(i + k - 1, n - 1)so the final partial group never reads past the end of the array. - The inner
whileloop performs the classic two-pointer swap, movingleftforward andrightbackward until they meet. - Because every swap happens inside the input array, the function mutates
arrdirectly and returns nothing.
Step-by-Step Trace
Let’s trace the algorithm on a small input where the last group is partial, arr = {10, 20, 30, 40, 50} and k = 2. The expected output is {20, 10, 40, 30, 50}.
| Group start i | left, right | Action | Array after group |
|---|---|---|---|
| 0 | 0, 1 | swap arr[0] and arr[1] | {20, 10, 30, 40, 50} |
| 2 | 2, 3 | swap arr[2] and arr[3] | {20, 10, 40, 30, 50} |
| 4 | 4, 4 | left not less than right, no swap | {20, 10, 40, 30, 50} |
At the end of each outer iteration, the slice arr[0..i + k - 1] holds the fully reversed prefix of all completed groups, and the elements beyond index i + k - 1 are untouched. That invariant is what guarantees the final array is correct once the outer loop ends.
Examples
Here are three worked examples that show how the method behaves across different shapes of input and k.
Example 1: Group Size Divides the Length
int[] arr = {1, 2, 3, 4, 5, 6};
int k = 2;
reverseInGroups(arr, k);
System.out.println(Arrays.toString(arr));
// Output: [2, 1, 4, 3, 6, 5]Example 2: Last Group Is Partial
int[] arr = {1, 2, 3, 4, 5};
int k = 3;
reverseInGroups(arr, k);
System.out.println(Arrays.toString(arr));
// Output: [3, 2, 1, 5, 4]Example 3: K Larger Than the Array
int[] arr = {1, 2, 3};
int k = 5;
reverseInGroups(arr, k);
System.out.println(Arrays.toString(arr));
// Output: [3, 2, 1]Common Mistakes to Avoid
Even though the algorithm is short, there are a handful of errors that trip up most first attempts. Each one has a clear symptom you can look for in your own code.
- Reading past the end on the last group – using
arr[i + k - 1]as the right pointer directly throwsArrayIndexOutOfBoundsExceptionwhenevernis not a multiple ofk. Always clamp withMath.min(i + k - 1, n - 1). - Advancing i by one instead of k – using
i++instead ofi += kre-reverses the same group over and over and produces a nearly unchanged array. Advanceibykat the end of each outer iteration. - Looping while left is less than or equal to right – swapping when
left == rightis harmless but wasteful, and if combined with a stale copy ofrightit can overshoot. Stick with the strictleft < rightcondition. - Not validating k – a
kvalue of0or a negative number keepsiat0forever and the outer loop never terminates. Return early whenk <= 1sincek = 1would reverse groups of size one, which is a no-op anyway. - Allocating a new array for every group – creating a fresh
int[k]inside the loop defeats the in-place design and raises space complexity toO(k). Reuse a singletempvariable and swap in place.
Edge Cases to Test
Walk through these inputs before you call the problem done. They are the ones interviewers tend to prompt for explicitly.
- Empty array
- Single-element array
kequal to1kequal to the array lengthkgreater than the array length- Array length not divisible by
k kequal to0or a negative value- Null array reference
Additional Considerations
The time complexity of reverseInGroups is O(n) because every element is visited at most twice, once by the outer loop pointer and once by the inner swap. The space complexity is O(1) since the only extra memory is the temp variable used for swapping.
Mutating the input is a deliberate choice. It keeps memory flat and matches how most interviewers phrase the problem, but it does mean the caller loses the original ordering. If that trade-off is unacceptable, copy the array first with Arrays.copyOf(arr, arr.length) and reverse the copy.
The null and non-positive k checks at the top are deliberately placed before any index arithmetic. Doing them later risks leaking a confusing exception from inside the loop rather than a clean, early return at the boundary.
Interview Follow-up Questions
A good interviewer rarely stops at the base problem. Expect one or more of these variants, which are ordered from gentler to harder.
- How would you reverse only alternate groups of k? – Toggle a boolean flag at the start of each outer iteration and skip the inner swap loop when the flag is off.
- How would you solve this for a singly linked list instead of an array? – Walk
knodes at a time, reverse the sublist by rewiringnextpointers, and splice it back to the previous group’s tail; no extra memory is needed. - What if the input arrives as a stream of unknown length? – Buffer up to
kvalues, emit them in reverse when the buffer fills, and flush whatever is left when the stream ends. - How would you return a reversed copy without touching the input? – Allocate a new array and compute each destination index as the mirror of the source inside its group, which avoids any in-place swaps.
- How would you handle a very large k, say up to one billion? – Clamp
ktoMath.min(k, n)once at entry; the inner loop then runs at mostn / 2swaps and the overall complexity staysO(n).
Conclusion
Reversing an array in groups of K comes down to two ideas working together, an outer loop that steps by k and an inner two-pointer swap bounded by a safe clamp on the right index. Once you internalize that pattern you can adapt it to linked lists, streams, and immutable variants without rewriting the core logic.
Try the program with your own inputs, especially the edge cases listed above, and verify that the output matches what you traced by hand. The muscle memory you build on this problem pays off directly on reverse a linked list in groups of k, rotate an array, and many sliding-window interview questions.
You can learn more about Array algorithms and interview-ready problems: Arrays.



