Python Program for array rotation

In this article, we will learn how to rotate an array by a given number of positions. Array rotation is a fundamental operation where elements are shifted left or right, with elements that fall off one end being placed at the other end.

Problem statement ? Given an array and a number of positions, we need to rotate the array elements by the specified number of positions.

Original Array: 1 2 3 4 5 Rotate by 2 After Rotation: 4 5 1 2 3

Using Slicing (Left Rotation)

The simplest approach uses Python's slicing to rotate an array to the left ?

def rotate_left(arr, positions):
    n = len(arr)
    positions = positions % n  # Handle positions greater than array length
    return arr[positions:] + arr[:positions]

# Example usage
numbers = [1, 2, 3, 4, 5]
rotated = rotate_left(numbers, 2)
print("Original array:", numbers)
print("After left rotation by 2:", rotated)
Original array: [1, 2, 3, 4, 5]
After left rotation by 2: [3, 4, 5, 1, 2]

Using Slicing (Right Rotation)

For right rotation, we move elements in the opposite direction ?

def rotate_right(arr, positions):
    n = len(arr)
    positions = positions % n  # Handle positions greater than array length
    return arr[-positions:] + arr[:-positions]

# Example usage
numbers = [1, 2, 3, 4, 5]
rotated = rotate_right(numbers, 2)
print("Original array:", numbers)
print("After right rotation by 2:", rotated)
Original array: [1, 2, 3, 4, 5]
After right rotation by 2: [4, 5, 1, 2, 3]

In-Place Rotation Using Reverse

This method uses array reversal to achieve rotation without extra space ?

def reverse_array(arr, start, end):
    while start < end:
        arr[start], arr[end] = arr[end], arr[start]
        start += 1
        end -= 1

def rotate_left_inplace(arr, positions):
    n = len(arr)
    positions = positions % n
    
    # Reverse entire array
    reverse_array(arr, 0, n - 1)
    # Reverse first n-positions elements
    reverse_array(arr, 0, n - positions - 1)
    # Reverse last positions elements
    reverse_array(arr, n - positions, n - 1)

# Example usage
numbers = [1, 2, 3, 4, 5]
print("Original array:", numbers)
rotate_left_inplace(numbers, 2)
print("After in-place left rotation by 2:", numbers)
Original array: [1, 2, 3, 4, 5]
After in-place left rotation by 2: [3, 4, 5, 1, 2]

Comparison of Methods

Method Time Complexity Space Complexity Modifies Original
Slicing O(n) O(n) No
In-place Reverse O(n) O(1) Yes

Conclusion

Array rotation can be implemented using slicing for simplicity or in-place reversal for memory efficiency. Use slicing when you want to preserve the original array, and in-place methods when memory is a constraint.

---
Updated on: 2026-03-25T06:48:46+05:30

290 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements