Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program for Reversal algorithm for array rotation
The reversal algorithm for array rotation is an efficient technique that rotates an array by reversing specific portions. This algorithm achieves left rotation by performing three strategic reversals instead of moving elements one by one.
How the Reversal Algorithm Works
To rotate an array left by d positions:
- Reverse the first
delements - Reverse the remaining elements
- Reverse the entire array
Example
Here's the complete implementation of the reversal algorithm ?
def reverse_list(arr, begin, end):
while (begin < end):
temp = arr[begin]
arr[begin] = arr[end]
arr[end] = temp
begin += 1
end = end - 1
def left_rotate(arr, to_rotate):
n = len(arr)
reverse_list(arr, 0, to_rotate - 1)
reverse_list(arr, to_rotate, n - 1)
reverse_list(arr, 0, n - 1)
def print_array(arr):
for i in range(0, len(arr)):
print(arr[i])
# Example usage
numbers = [34, 42, 56, 78, 9, 0, 23]
print("Original array:")
print(numbers)
print("\nRotating left by 3 positions...")
left_rotate(numbers, 3)
print("\nArray after rotation:")
print_array(numbers)
Original array: [34, 42, 56, 78, 9, 0, 23] Rotating left by 3 positions... Array after rotation: 78 9 0 23 34 42 56
Step-by-Step Process
Let's trace through the algorithm with array [34, 42, 56, 78, 9, 0, 23] rotating left by 3 positions ?
def demonstrate_steps():
arr = [34, 42, 56, 78, 9, 0, 23]
print("Original:", arr)
# Step 1: Reverse first 3 elements
arr[0:3] = reversed(arr[0:3])
print("After reversing first 3:", arr)
# Step 2: Reverse remaining elements
arr[3:] = reversed(arr[3:])
print("After reversing remaining:", arr)
# Step 3: Reverse entire array
arr.reverse()
print("After reversing entire array:", arr)
demonstrate_steps()
Original: [34, 42, 56, 78, 9, 0, 23] After reversing first 3: [56, 42, 34, 78, 9, 0, 23] After reversing remaining: [56, 42, 34, 23, 0, 9, 78] After reversing entire array: [78, 9, 0, 23, 34, 42, 56]
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(n) | Each element is visited exactly twice |
| Space | O(1) | Only uses temporary variables |
Conclusion
The reversal algorithm efficiently rotates arrays in O(n) time with O(1) space complexity. It's particularly useful for large arrays where memory efficiency is important, using three strategic reversals instead of element-by-element movement.
Advertisements
