Open In App
Related Articles

Print array after it is right rotated K times

Improve Article
Improve
Save Article
Save
Like Article
Like

Given an Array of size N and a values K, around which we need to right rotate the array. How to quickly print the right rotated array?
Examples : 

Input: Array[] = {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: Array[] = {1, 2, 3, 4, 5}, K = 4.
Output: 2 3 4 5 1

Approach:

  1. We will first take mod of K by N (K = K % N) because after every N rotation array will become the same as the initial array. 
  2. Now, we will iterate the array from i = 0 to i = N-1 and check, 
    • If i < K, Print rightmost Kth element (a[N + i -K]). 
    • Otherwise, Print array after ‘K’ elements (a[i – K]). 
       

Below is the implementation of the above approach. 

C++




// C++ implementation of right rotation
// of an array K number of times
#include<bits/stdc++.h>
using namespace std;
 
// Function to rightRotate array
void RightRotate(int a[], int n, int k)
{
     
    // If rotation is greater
    // than size of array
    k = k % n;
 
    for(int i = 0; i < n; i++)
    {
       if(i < k)
       {
            
           // Printing rightmost
           // kth elements
           cout << a[n + i - k] << " ";
       }
       else
       {
            
           // Prints array after
           // 'k' elements
           cout << (a[i - k]) << " ";
       }
    }
    cout << "\n";
}
     
// Driver code
int main()
{
    int Array[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(Array) / sizeof(Array[0]);
    int K = 2;
     
    RightRotate(Array, N, K);
}
 
// This code is contributed by Surendra_Gangwar


Java




// Java Implementation of Right Rotation
// of an Array K number of times
import java.util.*;
import java.lang.*;
import java.io.*;
 
class Array_Rotation
{
 
// Function to rightRotate array
static void RightRotate(int a[],
                        int n, int k)
{
     
    // If rotation is greater
    // than size of array
    k=k%n;
 
    for(int i = 0; i < n; i++)
    {
        if(i<k)
        {
            // Printing rightmost
            // kth elements
            System.out.print(a[n + i - k]
                             + " ");
        }
        else
        {
            // Prints array after
            // 'k' elements
            System.out.print(a[i - k]
                             + " ");
        }
    }
    System.out.println();
}
     
// Driver program
public static void main(String args[])
{
    int Array[] = {1, 2, 3, 4, 5};
    int N = Array.length;
 
    int K = 2;
    RightRotate(Array, N, K);
 
}
}
// This code is contributed by M Vamshi Krishna


Python3




# Python3 implementation of right rotation
# of an array K number of times
 
# Function to rightRotate array
def RightRotate(a, n, k):
 
    # If rotation is greater
    # than size of array
    k = k % n;
 
    for i in range(0, n):
 
        if(i < k):
 
            # Printing rightmost
            # kth elements
            print(a[n + i - k], end = " ");
 
        else:
 
            # Prints array after
            # 'k' elements
            print(a[i - k], end = " ");
 
    print("\n");
 
# Driver code
Array = [ 1, 2, 3, 4, 5 ];
N = len(Array);
K = 2;
     
RightRotate(Array, N, K);
 
# This code is contributed by Code_Mech


C#




// C# implementation of right rotation
// of an array K number of times
using System;
class GFG{
 
// Function to rightRotate array
static void RightRotate(int []a,
                        int n, int k)
{
 
    // If rotation is greater
    // than size of array
    k = k % n;
 
    for(int i = 0; i < n; i++)
    {
       if(i < k)
       {
            
           // Printing rightmost
           // kth elements
           Console.Write(a[n + i - k] + " ");
       }
       else
       {
            
           // Prints array after
           // 'k' elements
           Console.Write(a[i - k] + " ");
       }
    }
    Console.WriteLine();
}
     
// Driver code
public static void Main(String []args)
{
    int []Array = { 1, 2, 3, 4, 5 };
    int N = Array.Length;
    int K = 2;
     
    RightRotate(Array, N, K);
}
}
 
// This code is contributed by Rohit_ranjan


Javascript




// Javascript implementation of right rotation
// of an array K number of times
 
// Function to rightRotate array
function RightRotate(a, n, k)
{
 
    // If rotation is greater
    // than size of array
    k = k % n;
 
    for (let i = 0; i < n; i++) {
        if (i < k) {
 
            // Printing rightmost
            // kth elements
            document.write(a[n + i - k] + " ");
        }
        else {
 
            // Prints array after
            // 'k' elements
            document.write((a[i - k]) + " ");
        }
    }
    document.write("<br>");
}
 
// Driver code
let Array = [1, 2, 3, 4, 5];
let N = Array.length;
let K = 2;
 
RightRotate(Array, N, K);
 
// This code is contributed by gfgking.


Output

4 5 1 2 3 



Time complexity : O(n) 
Auxiliary Space : O(1)
 

Method 2: Reversing the array 

Approach: The approach is simple yet optimized. The idea is to reverse the array three times. For the first time we reverse only the last k elements. Second time we will reverse first n-k(n=size of array) elements. Finally we will get our rotated array by reversing the entire array.

Code:

C++




// C++ program to rotate right an array  by K times
#include <iostream>
using namespace std;
int main()
{
    int arr[] = { 1, 3, 5, 7, 9, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3; //No. of rotations
    k = k % n;
    int i, j;
    // Reverse last k numbers
    for (i = n - k, j = n - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    // Reverse the first n-k terms
    for (i = 0, j = n - k - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    // Reverse the entire array
    for (i = 0, j = n - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 
    // Print the rotated array
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
 
    return 0;
}


C




// C program to rotate right an array  by K times
#include <stdio.h>
// using namespace std;
int main()
{
    int arr[] = { 1, 3, 5, 7, 9, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3; //No. of rotations
    k = k % n;
    int i, j;
    // Reverse last k numbers
    for (i = n - k, j = n - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    // Reverse the first n-k terms
    for (i = 0, j = n - k - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    // Reverse the entire array
    for (i = 0, j = n - 1; i < j; i++, j--) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 
    // Print the rotated array
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
 
    return 0;
}


Java




// JAVA program to rotate right an array  by K times
import java.io.*;
class GFG {
    public static void main(String[] args)
    {
        int arr[] = new int[] { 1, 3, 5, 7, 9, 11 };
        int n = arr.length;
        int k = 3; // No. of rotations
        k = k % n;
        int i, j;
        // Reverse last k numbers
        for (i = n - k, j = n - 1; i < j; i++, j--) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        // Reverse the first n-k terms
        for (i = 0, j = n - k - 1; i < j; i++, j--) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
        // Reverse the entire array
        for (i = 0, j = n - 1; i < j; i++, j--) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
 
        // Print the rotated array
        for (int t = 0; t < n; t++) {
            System.out.print(arr[t] + " ");
        }
    }
}
 
// This code is contributed by Taranpreet


Python3




class GFG :
    @staticmethod
    def main( args) :
        arr = [1, 3, 5, 7, 9, 11]
        n = len(arr)
        k = 3
        # No. of rotations
        k = k % n
        i = 0
        j = 0
        # Reverse last k numbers
        i = n - k
        j = n - 1
        while (i < j) :
            temp = arr[i]
            arr[i] = arr[j]
            arr[j] = temp
            i += 1
            j -= 1
        # Reverse the first n-k terms
        i = 0
        j = n - k - 1
        while (i < j) :
            temp = arr[i]
            arr[i] = arr[j]
            arr[j] = temp
            i += 1
            j -= 1
        # Reverse the entire array
        i = 0
        j = n - 1
        while (i < j) :
            temp = arr[i]
            arr[i] = arr[j]
            arr[j] = temp
            i += 1
            j -= 1
        # Print the rotated array
        t = 0
        while (t < n) :
            print(str(arr[t]) + " ", end ="")
            t += 1
     
 
if __name__=="__main__":
    GFG.main([])
     
    # This code is contributed by aadityaburujwale.


C#




// C# program to rotate right an array by K times
using System;
 
public class GFG{
  public static void Main(String []args)
  {
    int []arr = { 1, 3, 5, 7, 9, 11 };
    int n = arr.Length;
    int k = 3; // No. of rotations
    k = k % n;
    int i, j;
 
    // Reverse last k numbers
    for (i = n - k, j = n - 1; i < j; i++, j--) {
      int temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
    // Reverse the first n-k terms
    for (i = 0, j = n - k - 1; i < j; i++, j--) {
      int temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
    // Reverse the entire array
    for (i = 0, j = n - 1; i < j; i++, j--) {
      int temp = arr[i];
      arr[i] = arr[j];
      arr[j] = temp;
    }
 
    // Print the rotated array
    for (int t = 0; t < n; t++) {
      Console.Write(arr[t] + " ");
    }
  }
}
 
// This code is contributed by Pushpesh Raj.


Javascript




// Javascript program to rotate right an array by K times
    let arr = [ 1, 3, 5, 7, 9, 11 ];
    let n = arr.length;
    let k = 3; //No. of rotations
    k = k % n;
    let i, j;
     
    // Reverse last k numbers
    for (i = n - k, j = n - 1; i < j; i++, j--) {
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
     
    // Reverse the first n-k terms
    for (i = 0, j = n - k - 1; i < j; i++, j--) {
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    // Reverse the entire array
    for (i = 0, j = n - 1; i < j; i++, j--) {
        let temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 
    // Print the rotated array
    for (let i = 0; i < n; i++) {
        console.log(arr[i]+ " ");
    }
 
    // This code is contributed by Aman Kumar


Output

7 9 11 1 3 5 



Complexity Analysis:

Time Complexity: O(N).

Auxiliary Space: O(1).

Approach 3: Recursive approach

Algorithm :

Here is the step-by-step algorithm .

  1. “rotateArray” function will take an array “arr” ,  it’s size is “n”  and the number of rotations “k” as an input.
  2.  To reduce the number of rotations, we compute ‘k’ modulo ‘n’ ( k%=n) .
  3. Using the STL library’s “reverse” function, reverse the first portion of the array from the start up to the “n – k” index.
  4. Using the “reverse” function from the STL library, reverse the second part of the array from the “n – k” index to the end.
  5. To get the rotated array, reverse the entire array using the “reverse” function in the STL library.
  6. Then ,we’ll return the rotated array.

Here is the pseudocode for the above algorithm:

function rotateArray(arr, n, k):
   // Reduce the number of rotations
   k = k % n

   // Reverse the first part of the array
   reverse(arr, arr + n – k)

   // Reverse the second part of the array
   reverse(arr + n – k, arr + n)

   // Reverse the entire array
   reverse(arr, arr + n)

// Driver code
arr = {1, 3, 5, 7, 9}
n = size(arr)
k = 2

rotateArray(arr, n, k)

for i = 0 to n-1:
   print arr[i]

// This  is contributed by  Vaibhav Saroj

Here is the implementation of pseudocode:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Function to rotate the array
void rotateArray(int arr[], int n, int k) {
    // Reduce the number of rotations
    k %= n;
 
    // Reverse the first part of the array
    reverse(arr, arr + n - k);
 
    // Reverse the second part of the array
    reverse(arr + n - k, arr + n);
 
    // Reverse the entire array
    reverse(arr, arr + n);
}
 
// Driver code
int main() {
    int arr[] = {1, 3, 5, 7, 9};
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 2;
 
    rotateArray(arr, n, k);
 
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
 
    return 0;
}
 
// This code is contributed by  Vaibhav Saroj


C




#include <stdio.h>
 
// Function to rotate the array
void rotateArray(int arr[], int n, int k) {
    if (k == 0) {
        return;
    }
 
    // rotate the array to the right by one position
    int temp = arr[n-1];
    for (int i = n-1; i > 0; i--) {
        arr[i] = arr[i-1];
    }
    arr[0] = temp;
 
    // recursively rotate the remaining elements k-1 times
    rotateArray(arr, n, k-1);
}
 
// Driver code
int main() {
    int arr[] = {1, 3, 5, 7, 9};
    int n = sizeof(arr)/sizeof(arr[0]);
    int k = 2;
 
    rotateArray(arr, n, k);
 
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
 
    return 0;
}
 
// This code is contributed by  Vaibhav Saroj


Java




import java.util.Arrays;
 
public class GFG {
 
    // Function to rotate the array
    static void rotateArray(int[] arr, int n, int k) {
        // Reduce the number of rotations
        k %= n;
 
        // Reverse the first part of the array
        reverse(arr, 0, n - k - 1);
 
        // Reverse the second part of the array
        reverse(arr, n - k, n - 1);
 
        // Reverse the entire array
        reverse(arr, 0, n - 1);
    }
 
    // Function to reverse a portion of the array
    static void reverse(int[] arr, int start, int end) {
        while (start < end) {
            // Swap elements at start and end
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
 
            // Move to the next pair of elements
            start++;
            end--;
        }
    }
 
    // Driver code
    public static void main(String[] args) {
        int[] arr = {1, 3, 5, 7, 9};
        int n = arr.length;
        int k = 2;
 
        rotateArray(arr, n, k);
 
        for (int i = 0; i < n; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }
}


Python3




def rotate_array(arr, n, k):
    # Reduce the number of rotations
    k %= n
 
    # Reverse the first part of the array
    arr[:n - k] = arr[:n - k][::-1]
 
    # Reverse the second part of the array
    arr[n - k:] = arr[n - k:][::-1]
 
    # Reverse the entire array
    arr[:] = arr[::-1]
 
 
# Driver code
arr = [1, 3, 5, 7, 9]
n = len(arr)
k = 2
 
rotate_array(arr, n, k)
 
for i in range(n):
    print(arr[i], end=" ")
 
print()
 
# This code is contributed by Dwaipayan Bandyopadhyay


Output

7 9 1 3 5 




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

Please see following posts for other methods of array rotation: 

https://www.geeksforgeeks.org/print-array-after-it-is-right-rotated-k-times-set-2/


Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!

Last Updated : 24 Aug, 2023
Like Article
Save Article
Similar Reads
Related Tutorials