Python Program for Reversal Algorithm for Array Rotation (original) (raw)

Last Updated : 30 Oct, 2025

Array rotation means shifting array elements to the left or right by a given number of positions.

**Example:

**Input: arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2
**Output: arr[] = [3, 4, 5, 6, 7, 1, 2]

Let's explore different methods for array rotation one by one:

Using reverse() Function

This method implements the Reversal Algorithm using Python’s built-in reverse() function. It divides the array into two parts based on rotation count d, reverses each part and then reverses whole array to get the rotated result.

Python `

arr = [1, 2, 3, 4, 5, 6, 7] d = 2 n = len(arr)

Reverse first d elements

arr[:d] = reversed(arr[:d])

Reverse remaining elements

arr[d:] = reversed(arr[d:])

Reverse entire array

arr.reverse() print(arr)

`

Output

[3, 4, 5, 6, 7, 1, 2]

**Explanation:

Using collections.deque

deque from the collections module allows fast appends and pops from both ends. It includes a rotate() method that can efficiently rotate elements left or right.

Python `

from collections import deque arr = [1, 2, 3, 4, 5, 6, 7] d = 2

res = deque(arr) res.rotate(-d) print(list(res))

`

Output

[3, 4, 5, 6, 7, 1, 2]

**Explanation:

Using Array Slicing

This method uses Python slicing to directly rearrange parts of the array. It’s concise but creates new lists during slicing, so it’s less memory efficient.

Python `

arr = [1, 2, 3, 4, 5, 6, 7] d = 2 res = arr[d:] + arr[:d] print(res)

`

Output

[3, 4, 5, 6, 7, 1, 2]

Using Manual Swap Method

This is the manual form of the reversal algorithm where we swap elements manually using loops.

Python `

arr = [1, 2, 3, 4, 5, 6, 7] d = 2 n = len(arr)

Reverse first part

start, end = 0, d - 1 while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1

Reverse second part

start, end = d, n - 1 while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1

Reverse full array

arr.reverse() print(arr)

`

Output

[3, 4, 5, 6, 7, 1, 2]