Given an array arr[] of size N and a value K, the task is to print the array rotated by K times to the right.
Examples:
Input: arr = {1, 3, 5, 7, 9}, K = 2
Output: 7 9 1 3 5Input: arr = {1, 2, 3, 4, 5}, K = 4
Output: 2 3 4 5 1Â
Algorithm: The given problem can be solved by reversing subarrays. Below steps can be followed to solve the problem:
- Reverse all the array elements from 1 to N -1
- Reverse the array elements from 1 to K – 1
- Reverse the array elements from K to N -1
C++
// C++ implementation for the above approach Â
#include <bits/stdc++.h> using namespace std; Â
// Function to rotate the array // to the right, K times void RightRotate( int Array[], int N, int K) { Â
    // Reverse all the array elements     reverse(Array, Array + N); Â
    // Reverse the first k elements     reverse(Array, Array + K); Â
    // Reverse the elements from K     // till the end of the array     reverse(Array + K, Array + N); Â
    // Print the array after rotation     for ( int i = 0; i < N; i++) { Â
        cout << Array[i] << " " ;     } Â
    cout << endl; } Â
// Driver code int main() { Â
    // Initialize the array     int Array[] = { 1, 2, 3, 4, 5 }; Â
    // Find the size of the array     int N = sizeof (Array) / sizeof (Array[0]); Â
    // Initialize K     int K = 4; Â
    // Call the function and     // print the answer     RightRotate(Array, N, K); Â
    return 0; } |
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG {        // Function to rotate the array     // to the right, K times     static void RightRotate( int [] Array, int N, int K)     { Â
        // Reverse all the array elements         for ( int i = 0 ; i < N / 2 ; i++) {             int temp = Array[i];             Array[i] = Array[N - i - 1 ];             Array[N - i - 1 ] = temp;         } Â
        // Reverse the first k elements         for ( int i = 0 ; i < K / 2 ; i++) {             int temp = Array[i];             Array[i] = Array[K - i - 1 ];             Array[K - i - 1 ] = temp;         } Â
        // Reverse the elements from K         // till the end of the array         for ( int i = 0 ; i < (N-K) / 2 ; i++) {             int temp = Array[(i + K)];             Array[(i + K)] = Array[(N - i - 1 )];             Array[(N - i - 1 )] = temp;         } Â
        // Print the array after rotation         for ( int i = 0 ; i < N; i++) { Â
            System.out.print(Array[i] + " " );         } Â
        System.out.println();     } Â
    // Driver code     public static void main(String[] args)     {                // Initialize the array         int Array[] = { 1 , 2 , 3 , 4 , 5 }; Â
        // Find the size of the array         int N = Array.length; Â
        // Initialize K         int K = 4 ; Â
        // Call the function and         // print the answer         RightRotate(Array, N, K);     } } Â
// This code is contributed by maddler. |
Python3
# Python program for the above approach import math Â
# Function to rotate the array # to the right, K times def RightRotate(Array, N, K): Â
    # Reverse all the array elements     for i in range (math.ceil(N / 2 )):         temp = Array[i]         Array[i] = Array[N - i - 1 ]         Array[N - i - 1 ] = temp Â
    # Reverse the first k elements     for i in range (math.ceil(K / 2 )):         temp = Array[i]         Array[i] = Array[K - i - 1 ]         Array[K - i - 1 ] = temp Â
    # Reverse the elements from K     # till the end of the array     for i in range (math.ceil((N - K) / 2 )):         temp = Array[(i + K)]         Array[(i + K)] = Array[(N - i - 1 )]         Array[(N - i - 1 )] = temp Â
    # Print the array after rotation     for i in range (N):         print (Array[i], end = " " ) Â
Â
# Driver Code arr = [ 1 , 2 , 3 , 4 , 5 ] N = len (arr) K = 4 Â
# Call the function and # print the answer RightRotate(arr, N, K) Â
# This code is contributed by Saurabh Jaiswal |
C#
// C# program for the above approach using System; class GFG {     // Function to rotate the array     // to the right, K times     static void RightRotate( int []Array, int N, int K)     { Â
        // Reverse all the array elements         for ( int i = 0; i < N / 2; i++) {             int temp = Array[i];             Array[i] = Array[N - i - 1];             Array[N - i - 1] = temp;         } Â
        // Reverse the first k elements         for ( int i = 0; i < K / 2; i++) {             int temp = Array[i];             Array[i] = Array[K - i - 1];             Array[K - i - 1] = temp;         } Â
        // Reverse the elements from K         // till the end of the array         for ( int i = 0; i < (N-K) / 2; i++) {             int temp = Array[(i + K)];             Array[(i + K)] = Array[(N - i - 1)];             Array[(N - i - 1)] = temp;         } Â
        // Print the array after rotation         for ( int i = 0; i < N; i++) { Â
            Console.Write(Array[i] + " " );         }     } Â
    // Driver code     public static void Main()     {                // Initialize the array         int []Array = { 1, 2, 3, 4, 5 }; Â
        // Find the size of the array         int N = Array.Length; Â
        // Initialize K         int K = 4; Â
        // Call the function and         // print the answer         RightRotate(Array, N, K);     } } // This code is contributed by Samim Hossain Mondal. |
Javascript
<script> // Javascript program for the above approach Â
// Function to rotate the array // to the right, K times function RightRotate(Array, N, K) { Â
    // Reverse all the array elements     for (let i = 0; i < N / 2; i++) {         let temp = Array[i];         Array[i] = Array[N - i - 1];         Array[N - i - 1] = temp;     }  Â
    // Reverse the first k elements     for (let i = 0; i < K / 2; i++) {         let temp = Array[i];         Array[i] = Array[K - i - 1];         Array[K - i - 1] = temp;     } Â
    // Reverse the elements from K     // till the end of the array     for (let i = 0; i < (N-K) / 2; i++) {         let temp = Array[(i + K)];         Array[(i + K)] = Array[(N - i - 1)];         Array[(N - i - 1) % N] = temp;     } Â
    // Print the array after rotation     for (let i = 0; i < N; i++) {         document.write(Array[i] + " " );     } } Â
// Driver Code Â
let arr = [ 1, 2, 3, 4, 5 ]; let N = arr.length; let K =4; Â
// Call the function and // print the answer RightRotate(arr, N, K); Â
// This code is contributed by Samim Hossain Mondal. </script> |
2 3 4 5 1
Time Complexity: O(N) Â
Auxiliary Space: O(1)
Print array after it is right rotated K times using Recursion
Step-by-step approach:
- If “k” = 0, return the array “arr” and terminate the recursion.
- Else, move the last element to the first position and rotate the array “arr” to the right by one position by moving each element one position to the right.
- Recursively call the “rotateArray()” function with the same array “arr”, of size “n”, and k-1.
- Return the rotated array “arr” and terminate the recursion.
Below is the implementation of the above Recursive approach:Â
C++
// C++ implementation for Print array after it is right // rotated K times using Recursion Â
#include <bits/stdc++.h> using namespace std; Â
// 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++) {         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.*; Â
public class Main {          // Function to rotate the array     public static 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     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();     } } Â
// This code is contributed by Vaibhav Saroj |
C#
// C# code using System; Â
public class GFG {          // Function to rotate the array     public static 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     public static void Main() {         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++) {             Console.Write(arr[i] + " " );         }         Console.WriteLine();     } } Â
// This code is contributed by Utkarsh Kumar |
Javascript
function rotateArray(arr, n, k) {   if (k === 0) {     return ;   }      // rotate the array to the right by one position   const temp = arr[n-1];   for (let 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 const arr = [1, 3, 5, 7, 9]; const n = arr.length; const k = 2; Â
rotateArray(arr, n, k); Â
console.log(arr); // Output: [ 7, 9, 1, 3, 5 ] Â
Â
// This code is contributed by Vaibhav Saroj |
7 9 1 3 5
Time Complexity: O(k*n)
Auxiliary Space: O(k)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!