The Wayback Machine - https://web.archive.org/web/20220105224227/https://www.geeksforgeeks.org/right-rotate-given-array-k-times-using-pointers/
Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Right rotate given Array K times using Pointers

  • Last Updated : 05 Jan, 2022

Given an array arr[] of size N and an integer K, the task is to right rotate the array K times.

Examples: 

Resolution Days 2022 GeeksforGeeks

Input: arr[] = {1, 3, 5, 7, 9}, K = 2
Output: 7 9 1 3 5
Explanation: After 1st rotation – {9, 1, 3, 5, 7}
After 2nd rotation – {7, 9, 1, 3, 5}

Input: {1, 2, 3, 4, 5, 6}, K = 2
Output: 5 6 1 2 3 4



 

Approach: The naive approach and approach based on reversing parts of the array is discussed here.

Pointer based approach: The base of this concept is the reversal algorithm for array rotation. The array is divided into two parts where the first part is of size (N-K) and the end part is of size K. These two parts are individually reversed. Then the whole array is reversed.

Below is the implementation of the above approach:

C++




// C++ code to implement above approach
#include <iostream>
using namespace std;
  
// Function to print the array
void print(int arr[], int N)
{
    for (int i = 0; i < N; i++)
        cout << *(arr + i) << " ";
}
  
// Function to reverse the array
// from start to end index
void reverse(int arr[], int start, int end)
{
    int temp;
    int size = end - start;
  
    // Reversal based on pointer approach
    for (int i = 0; i < (size / 2); i++) {
        temp = *(arr + i + start);
        *(arr + i + start) = *(arr + start 
                             + size - i - 1);
        *(arr + start + size - i - 1) = temp;
    }
}
  
// Function to right rotate the array K times
void right(int arr[], int K, int N)
{
    reverse(arr, 0, N - K);
    reverse(arr, N - K, N);
    reverse(arr, 0, N);
    print(arr, N);
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
    int K = 2;
    right(arr, K, N);
    return 0;
}
Output
5 6 1 2 3 4 

Time Complexity: O(N)
Auxiliary Space: O(1)




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!