Input: arr[] = [1, 2, 3, 4, 5, 6, 7, 8], k = 3
Output: [3, 2, 1, 6, 5, 4, 8, 7]
Explanation: Elements is reversed: [1, 2, 3] → [3, 2, 1], [4, 5, 6] → [6, 5, 4], and the last group [7, 8]
(size < 3) is reversed as [8, 7]
.
Input: arr[] = [1, 2, 3, 4, 5], k = 3
Output: [3, 2, 1, 5, 4]
Explanation: First group consists of elements 1, 2, 3. Second group consists of 4, 5.
Input: arr[] = [5, 6, 8, 9], k = 5
Output: [9, 8, 6, 5]
Explnation: Since k is greater than array size, the entire array is reversed.
Idea is to 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.