Program for array rotation

Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements.

Method 1 Use temp array

  1. Store d elements in a temp array
  2. Shift rest of the arr[]
  3. Store back the d elements
void rotate(vector<int>& nums, int k) {
    k = k % nums.size();
    vector<int> temp;
    for(int i=nums.size()-k; i<nums.size(); i++) {
        temp.push_back(nums[i]);
    }

    for(int i=nums.size()-k-1; i>=0; i--) {
        nums[i+k] = nums[i];
    }

    for(int i=0; i<temp.size(); i++) {
        nums[i] = temp[i];
    }
}

Method 2 Using Reverse

This approach is based on the fact that when we rotate the array k times, k elements from the back end of the array come to the front and the rest of the elements from the front shift backwards.

void rotate(vector<int>& nums, int k) {
    int n = nums.size();
    k %= n;
    reverse(nums.begin(), nums.begin() + n - k) ;
    reverse(nums.begin() + n - k, nums.end());
    reverse(nums.begin(), nums.end());

}

Method 3 Rotate one by one

void rotateByOne(vector<int>& nums) {
    if(nums.size() <= 1) return;

    int temp = nums[nums.size()-1];
    for(int i=nums.size()-1; i>0; i--) {
        nums[i] = nums[i-1];
    }
    nums[0] = temp;
}

results matching ""

    No results matching ""