Python – Cyclically Rotate an Array by One Position
Cyclically rotating an array by one position means that the last element of the array moves to the front, and every other element shifts one position to the right.
Problem Statement
Given an array arr
of size n
, cyclically rotate the array by one position. In other words, after rotation, the array should be transformed to: [arr[n-1], arr[0], arr[1], ... , arr[n-2]
].
Sample Input and Output
Example 1:
</>
Copy
Input: arr = [1, 2, 3, 4, 5]
Output: [5, 1, 2, 3, 4]
Example 2:
</>
Copy
Input: arr = [10, 20, 30, 40]
Output: [40, 10, 20, 30]
Solution Approach
There are multiple ways to achieve the cyclic rotation. Below are two common approaches:
- Using Slicing: Create a new array by concatenating the last element with the rest of the array.
- Using a Loop: Store the last element, shift all other elements one position to the right, and then place the stored element at the beginning.
Python Program
Method 1: Using Slicing
</>
Copy
# Function to cyclically rotate an array using slicing
def rotate_array_slicing(arr):
if not arr:
return arr
return [arr[-1]] + arr[:-1]
# Sample Input
arr1 = [1, 2, 3, 4, 5]
print("Rotated Array:", rotate_array_slicing(arr1))
Output:
Rotated Array: [5, 1, 2, 3, 4]
Method 2: Using a Loop
This approach performs the rotation in-place by shifting each element to the right.
</>
Copy
# Function to cyclically rotate an array using a loop
def rotate_array_loop(arr):
n = len(arr)
if n == 0:
return arr
# Store the last element
last_element = arr[-1]
# Shift elements one position to the right
for i in range(n-1, 0, -1):
arr[i] = arr[i-1]
# Place the last element at the beginning
arr[0] = last_element
return arr
# Sample Input
arr2 = [10, 20, 30, 40]
print("Rotated Array:", rotate_array_loop(arr2))
Output:
Rotated Array: [40, 10, 20, 30]
Conclusion
Both methods effectively cyclically rotate an array by one position. The slicing method is concise and creates a new array, while the loop method performs the operation in-place with constant extra space.