3.6 Reverse Array in Groups in JavaScript
Basic Array Algorithm Problems in JavaScript
Full Course on Data Structures and Algorithms in JavaScript
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):
"use strict";
function reverseArrayInGroups(arr, k) {
let n = arr.length;
for (let i = 0; i < n; i += k) {
let left = i;
let right;
// 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
let temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
left++;
right--;
}
}
}
//main area
const arr = [0, 1, 2, 3, 4, 5, 6, 7];
let k = 3;
reverseArrayInGroups(arr, k);
for (let i = 0; i < arr.length; i++)
process.stdout.write(arr[i] + " ");
console.log();
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.