3.6 Reverse Array (List) in Groups in Python
Basic Array (List) Algorithm Problems in Python
Full Course on Data Structures and Algorithms in Python
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 reverseArrayInGroups(arr, k):
n = len(arr);
for i in range(0, n, k):
left = i;
right = n;
#to determine right value
if i+k-1 < n-1:
right = i+k-1; #zero based indexing
else:
right = 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;
#main area
arr = [0, 1, 2, 3, 4, 5, 6, 7];
k = 3;
reverseArrayInGroups(arr, k);
for i in range(0, len(arr)):
print(arr[i], end=" ");
print();
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.