Python program to right rotate the elements of an array
def right_rotate(arr, k):
k %= len(arr)
return arr[-k:] + arr[:-k]
# Example usage
arr = [1, 2, 3, 4, 5]
k = 2
print(right_rotate(arr, k))
The function right_rotate(arr, k)
takes an array arr
and an integer k
as arguments. It uses the modulus operator to ensure that k
is within the range of the length of the array. It creates a new array by concatenating the last k
elements of the original array with the elements before the last k
elements.
Method 2: Using collections.deque and rotate():
from collections import deque
def right_rotate(arr, k):
k %= len(arr)
dq = deque(arr)
dq.rotate(k)
return list(dq)
# Example usage
arr = [1, 2, 3, 4, 5]
k = 2
print(right_rotate(arr, k))
The function right_rotate(arr, k)
takes an array arr
and an integer k
as arguments. It uses the modulus operator to ensure that k
is within the range of the length of the array. It first creates a deque object from the given array, then use the rotate method to rotate the elements k
times to the right and finally returns the deque object as a list.
Both methods above will output: [4, 5, 1, 2, 3] for the given example.
Method 1 uses slicing and concatenation to shift the elements in the array, and Method 2 uses collections.deque and rotate() method to rotate the elements in the array.