Python Program to Rotate Array Left
d positions in Python, use slicing like rotated = arr[d:] + arr[:d] where arr is your list.Examples
How to Think About It
d positions, think of moving the first d elements to the end while keeping the order of the rest. You can split the array into two parts: from d to end, and from start to d, then join them in reverse order.Algorithm
Code
def rotate_left(arr, d): d = d % len(arr) # handle rotations greater than array length return arr[d:] + arr[:d] # Example usage array = [1, 2, 3, 4, 5] rotated_array = rotate_left(array, 2) print(rotated_array)
Dry Run
Let's trace rotating [1, 2, 3, 4, 5] left by 2 positions through the code
Calculate effective rotation
d = 2 % 5 = 2
Slice from d to end
arr[2:] = [3, 4, 5]
Slice from start to d
arr[:2] = [1, 2]
Concatenate slices
[3, 4, 5] + [1, 2] = [3, 4, 5, 1, 2]
| Step | Operation | Result |
|---|---|---|
| 1 | Calculate d % len(arr) | 2 |
| 2 | Slice arr[d:] | [3, 4, 5] |
| 3 | Slice arr[:d] | [1, 2] |
| 4 | Concatenate slices | [3, 4, 5, 1, 2] |
Why This Works
Step 1: Handle rotations larger than array length
Using d = d % len(arr) ensures the rotation count never exceeds the array size, avoiding unnecessary full rotations.
Step 2: Split the array into two parts
Slicing the array into arr[d:] and arr[:d] separates the part to move and the part to keep in front.
Step 3: Join slices to form rotated array
Concatenating arr[d:] + arr[:d] moves the first d elements to the end, completing the left rotation.
Alternative Approaches
from collections import deque def rotate_left_deque(arr, d): dq = deque(arr) dq.rotate(-d) # negative for left rotation return list(dq) print(rotate_left_deque([1, 2, 3, 4, 5], 2))
def rotate_left_pop(arr, d): for _ in range(d): first = arr.pop(0) arr.append(first) return arr print(rotate_left_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 all elements once.
Space Complexity
The rotated array is a new list, so it uses O(n) extra space.
Which Approach is Fastest?
Slicing is fast and simple for small to medium arrays; deque rotation is efficient for large data and in-place rotation; repeated popping is slow and not recommended for big arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Slicing | O(n) | O(n) | Simple and readable code |
| Deque rotation | O(n) | O(n) | Efficient for large arrays, in-place rotation |
| Repeated popping | O(n*d) | O(1) | Small arrays or learning purposes only |
arr[d:] + arr[:d] for a clean and fast left rotation in Python.d % len(arr) can cause errors when d is larger than the array length.