3.6 Reverse Array in Groups in Ruby
Basic Array Algorithm Problems in Ruby
Full Course on Data Structures and Algorithms in Ruby
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):
def reverse_array_in_groups(arr, k)
n = arr.length
i = 0
while i < n
left = i
# to determine right value
right = (i + k - 1 < n - 1) ? i + k - 1 : n - 1 #zero based indexing
# reverse the sub-array [left, right]
while left < right
# swap
temp = arr[left]
arr[left] = arr[right]
arr[right] = temp
left += 1
right -= 1
end
i += k
end
end
arr = [0, 1, 2, 3, 4, 5, 6, 7]
k = 3
reverse_array_in_groups(arr, k)
for i in 0...arr.length
print(arr[i], " ")
end
puts
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.