3.6 Reverse Array in Groups in R
Basic Array Algorithm Problems in R
Full Course on Data Structures and Algorithms in R
By: Chrysanthus Date Published: 3 Feb 2026
The reader is advised to read all the lessons (tutorials) in this full course, in the order presented.
Problem
Given an array, arr[] and an integer k=3, find the array after reversing every sub-array of consecutive k elements in place. If the last sub-array has fewer than k elements, reverse it as it is. Modify the array in place; do not return anything. The given array is:
[0, 1, 2, 3, 4, 5, 6, 7]
The algorithm should use O(n) time and O(n) space. The output should be:
[2, 1, 0, 5, 4, 3, 7, 6]
Solution
Edge Cases:
When k = 1, or k = 0, the array stays the same. When k is greater than or equal to the array size, the whole array is reversed.
Strategy
- Take the first edge case into consideration.
- Begin from index 0 and find the size of the current sub-array to be reversed. If the number of elements is less than k, reverse all of them.
- Each sub-array is reversed using two pointers (optionally) that start from the two corners of the sub-array.
In the function there is the principal for-loop, where increment of the index is done in k's.
Zero based indexing is used. The left included index of a group (sub-array) is obtained from,
int left = i;
where i is the iterating index. The right included index of a group (sub-array) is obtained from,
i+k-1 //zero based counting
where i is the iterating index (zero based).
The following program illustrates this (read through the code and comments):
reverseArrayInGroups <- function(arr, k) {
n = length(arr);
i <- 1;
while (i <= n) {
left <- i;
# to determine right value
if (i+k-1 < n) {
right = i+k-1; #one based indexing
} else {
right = n; #one based indexing
}
# reverse the sub-array [left, right]
while (left < right) {
# swap
temp <- arr[left];
arr[left] <- arr[right];
arr[right] <- temp;
left <- left + 1;
right <- right - 1;
}
i <- i + k; #incrementing with k
}
return(arr) # Return the modified array
}
#main area
arr = c(0, 1, 2, 3, 4, 5, 6, 7);
k = 3;
arr <- reverseArrayInGroups(arr, k); # Assign the returned array back
for (i in 1:length(arr))
cat(arr[i], " ", sep="");
cat("\n");
The output is:
2 1 0 5 4 3 7 6
Thanks for reading.
Related Links
More Related LinksCousins
BACK NEXTComments
Note: You can use the Search Box above to find articles and discussions of interest.