Broad Network


3.6 Reverse Vector in Groups in Rust

Basic Vector Algorithm Problems in Rust

Full Course on Data Structures and Algorithms in Rust

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 vector, arr[] and an integer k=3, find the vector after reversing every sub-vector of consecutive k elements in place. If the last sub-vector has fewer than k elements, reverse it as it is. Modify the vector in place; do not return anything. The given vector 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 vector stays the same.
When k is greater than or equal to the vector size, the whole vector is reversed. 

Strategy

- Take the first edge case into consideration.
- Begin from index 0 and find the size of the current sub-vector to be reversed. If the number of elements is less than k, reverse all of them.
- Each sub-vector is reversed using two pointers (optionally) that start from the two corners of the sub-vector.

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-vector) is obtained from,

    int left = i;

where i is the iterating index. The right included index of a group (sub-vector) 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):

    fn reverse_array_in_groups(vtr: &mut Vec<i32>, k: usize) {    //use reference to avoid unnecessary recopying of vector
        let n = vtr.len();
    
        for i in (0..n).step_by(k) {
            let mut left = i;
            let mut 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-vtray [left, right]
            while left < right {
                // swap
                let temp = vtr[left];
                vtr[left] = vtr[right];
                vtr[right] = temp;

                left += 1;
                right -= 1;
            }
        }
    }

fn main() {
    let mut vtr = vec![0, 1, 2, 3, 4, 5, 6, 7];
    let k = 3;
        
    reverse_array_in_groups(&mut vtr, k);    //use reference to avoid unnecessary recopying of vector
        
    for i in 0..vtr.len() {
        print!("{} ", vtr[i]);
    }
    println!();
}

The output is:

    2 1 0 5 4 3 7 6 

Thanks for reading.





Related Links

More Related Links

Cousins

BACK NEXT

Comments


Note: You can use the Search Box above to find articles and discussions of interest.