**Problem: **Reverse array in subset of N.

For example:

input: Array = [1,2,3,4,5,6,7,8,9], N = 3

output: [3,2,1,6,5,4,9,8,7]

The array is divided in 3 subsets [1,2,3], [4,5,6] and [7,8,9]. Now these subsets are reversed to get the final output. i.e. [3,2,1,6,5,4,9,8,7]

Reverse number: reverse a number in Java

## Algorithm to reverse array in subset of N:

Lets see an algorithm to reverse array in subset of N.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Lets A be the given array with size 'l' Lets N be the number of subsets which we want to reverse. 1. Iterate over A, N times (iterate one subset at a time) for i = 0 to l, step by N 1. Calculate right index of subset, rightIndex = i + N 2. Calulate left index of subset, leftIndex = i 3. while leftIndex < rightIndex 1. Swap right index value with left index value temp = A[leftIndex] A[leftIndex] = A[rightIndex] A[rightIndex] = temp End while End for |

**Java code: **Lets write Java code to reverse array in subset of N

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class ReverseArray { private static void reverseArray(int[] arr, int interval) { for (int i = 0; i < arr.length; i = i + interval) { int rightIndex = i + interval; int arrLen = arr.length; rightIndex = rightIndex > arrLen ? arrLen - 1 : (rightIndex - 1); int leftIndex = i; while (leftIndex < rightIndex) { int temp = arr[leftIndex]; arr[leftIndex++] = arr[rightIndex]; arr[rightIndex--] = temp; } } } public static void main(String[] args) { int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int interval = 3; reverseArray(arr, interval); for (int i : arr) { System.out.print(i + " "); } } } |

**Output:**

1 | 3 2 1 6 5 4 9 8 7 |

I hope you liked the solution.

Please comment for your questions and doubts.

Happy programming 🙂