Python Program for Reversal Algorithm for Array Rotation
Array rotation means shifting array elements to the left or right by a given number of positions.
Example:
Input: arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2
Output: arr[] = [3, 4, 5, 6, 7, 1, 2]
Let's explore different methods for array rotation one by one:
Using reverse() Function
This method implements the Reversal Algorithm using Python’s built-in reverse() function. It divides the array into two parts based on rotation count d, reverses each part and then reverses whole array to get the rotated result.
arr = [1, 2, 3, 4, 5, 6, 7]
d = 2
n = len(arr)
# Reverse first d elements
arr[:d] = reversed(arr[:d])
# Reverse remaining elements
arr[d:] = reversed(arr[d:])
# Reverse entire array
arr.reverse()
print(arr)
Output
[3, 4, 5, 6, 7, 1, 2]
Explanation:
- Step 1 reverses the first 2 elements -> [2, 1, 3, 4, 5, 6, 7]
- Step 2 reverses remaining elements -> [2, 1, 7, 6, 5, 4, 3]
- Step 3 reverses entire array -> [3, 4, 5, 6, 7, 1, 2]
Using collections.deque
deque from the collections module allows fast appends and pops from both ends. It includes a rotate() method that can efficiently rotate elements left or right.
from collections import deque
arr = [1, 2, 3, 4, 5, 6, 7]
d = 2
res = deque(arr)
res.rotate(-d)
print(list(res))
Output
[3, 4, 5, 6, 7, 1, 2]
Explanation:
- Convert list to deque for efficient rotation.
- Rotate left by d using rotate(-d).
- Convert back to list and print the result.
Using Array Slicing
This method uses Python slicing to directly rearrange parts of the array. It’s concise but creates new lists during slicing, so it’s less memory efficient.
arr = [1, 2, 3, 4, 5, 6, 7]
d = 2
res = arr[d:] + arr[:d]
print(res)
Output
[3, 4, 5, 6, 7, 1, 2]
Using Manual Swap Method
This is the manual form of the reversal algorithm where we swap elements manually using loops.
arr = [1, 2, 3, 4, 5, 6, 7]
d = 2
n = len(arr)
# Reverse first part
start, end = 0, d - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
# Reverse second part
start, end = d, n - 1
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
# Reverse full array
arr.reverse()
print(arr)
Output
[3, 4, 5, 6, 7, 1, 2]