Python Program to Rotate Array Right by N Positions
k positions in Python, use slicing like rotated = arr[-k:] + arr[:-k] where arr is your list and k is the number of rotations.Examples
How to Think About It
Algorithm
Code
def rotate_right(arr, k): n = len(arr) k = k % n return arr[-k:] + arr[:-k] # Example usage array = [1, 2, 3, 4, 5] rotated_array = rotate_right(array, 2) print(rotated_array)
Dry Run
Let's trace rotating [1, 2, 3, 4, 5] by 2 positions to the right.
Calculate length and adjust k
Length n = 5, k = 2 % 5 = 2
Slice last k elements
arr[-2:] = [4, 5]
Slice remaining elements
arr[:-2] = [1, 2, 3]
Concatenate slices
rotated = [4, 5] + [1, 2, 3] = [4, 5, 1, 2, 3]
| Step | Operation | Result |
|---|---|---|
| 1 | Calculate k % n | 2 |
| 2 | Slice last k elements | [4, 5] |
| 3 | Slice first n-k elements | [1, 2, 3] |
| 4 | Concatenate slices | [4, 5, 1, 2, 3] |
Why This Works
Step 1: Adjust rotation count
Using k % n ensures the rotation count fits within the array length, avoiding unnecessary full rotations.
Step 2: Split array using slicing
Slicing arr[-k:] gets the last k elements, and arr[:-k] gets the rest, preparing for rotation.
Step 3: Combine slices to rotate
Joining the last k elements before the rest moves them to the front, achieving the right rotation.
Alternative Approaches
from collections import deque def rotate_right_deque(arr, k): d = deque(arr) d.rotate(k) return list(d) print(rotate_right_deque([1, 2, 3, 4, 5], 2))
def rotate_right_pop(arr, k): n = len(arr) k = k % n for _ in range(k): last = arr.pop() arr.insert(0, last) return arr print(rotate_right_pop([1, 2, 3, 4, 5], 2))
Complexity: O(n) time, O(n) space
Time Complexity
Slicing and concatenation each take O(n) time because they process the whole array.
Space Complexity
The rotated array is created as a new list, so space is O(n). In-place rotation would reduce space but is more complex.
Which Approach is Fastest?
Using slicing is fast and clear for most cases. The deque method is also efficient and uses optimized C code internally.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Slicing | O(n) | O(n) | Simple and readable code |
| collections.deque rotate | O(n) | O(n) | Efficient built-in method |
| Repeated pop and insert | O(k*n) | O(1) | Small arrays or rotations, simple logic |
k % len(arr) to handle rotation counts larger than the array size.