Python Program to Print array after it is right rotated K times
Given an Array of size N and a value 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:
- 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.
- 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.
Python3
def RightRotate(a, n, k):
k = k % n
for i in range ( 0 , n):
if (i < k):
print (a[n + i - k], end = " " )
else :
print (a[i - k], end = " " )
print ("")
Array = [ 1 , 2 , 3 , 4 , 5 ]
N = len (Array)
K = 2
RightRotate(Array, N, K)
|
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!
Last Updated :
30 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...