VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-for-reversal-algorithm-for-array-rotation/

⇱ Python Program for Reversal Algorithm for Array Rotation - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python Program for Reversal Algorithm for Array Rotation

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.


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

Explanation:

  • Step 1 reverses the first 2 elements -> [2, 1, 3, 4, 5, 6, 7]
  • Step 2 reverses remaining elements -> [2, 1, 7, 6, 5, 4, 3]
  • Step 3 reverses entire array -> [3, 4, 5, 6, 7, 1, 2]

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.


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

Explanation:

  • Convert list to deque for efficient rotation.
  • Rotate left by d using rotate(-d).
  • Convert back to list and print the result.

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.


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.


Output
[3, 4, 5, 6, 7, 1, 2]
Comment
Article Tags:
Article Tags: