C++ Program to Print array after it is right rotated K times

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 rotations 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 ``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 << " ``"; ``} ``     ` `// 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 `

Output:Â
`4 5 1 2 3`

Â

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

Please refer complete article on Print array after it is right rotated K times for more details!

Previous
Next