Reverse Consecutive Elements - C++ Solution

1. Introduction

In this blog post, we explore an array manipulation problem involving reversing consecutive elements within a subarray. Given an integer array, the task is to reverse every group of consecutive 'm' elements within a specified subarray.

Problem

Given an integer array nums and three non-negative integers i, j, and m, the goal is to reverse every group of consecutive m elements in the subarray [i, j] of nums.

2. Solution Steps

1. Validate the input to ensure i, j, and m are within the bounds of the array.

2. Iterate over the subarray [i, j].

3. For each group of m elements in this subarray, perform an in-place reversal.

4. If the remaining elements are less than m, reverse all of them.

5. Continue this process until the entire subarray is processed.

3. Code Program

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

void reverseGroups(vector<int>& nums, int i, int j, int m) {
    // Ensure valid input
    if (i > j || i < 0 || j >= nums.size() || m <= 0) return;

    while (i < j) {
        int right = min(i + m - 1, j);
        for (int left = i; left < right; left++, right--) {
            swap(nums[left], nums[right]);
        }
        i += m;
    }
}

int main() {
    vector<int> nums = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int m = 3, i = 1, j = 7;
    reverseGroups(nums, i, j, m);

    // Output the modified array
    cout << "Modified Array: ";
    for (int num : nums) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

Output:

Modified Array: 1 4 3 2 7 6 5 8 9 10

Explanation:

The function reverseGroups modifies the array nums by reversing every group of m elements within the subarray [i, j]. It iterates over the specified subarray, reversing each group of m elements in place. In the case where the number of elements in the remaining part of the subarray is less than m, it reverses all of them. For the input array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], m = 3, i = 1, and j = 7, the modified array is [1, 4, 3, 2, 7, 6, 5, 8, 9, 10].


Comments