Python program to cyclically rotate an array by one

In this tutorial, you will learn how to cyclically rotate an array by one in Python. Arrays are homogeneous collections of elements. Because of its vast importance and uses arrays are the most famous data structures in a programming language. Programmers use arrays in different areas because of their functionalities. So all these create a need for a programmer to learn about arrays. Not only learn to become a good programmer one should able to play with arrays and should be ready to do any task that requires arrays.

Now here our task is to rotate array by one in a cyclic manner. It is one of the basic operations on the array but in many cases, it comes shady. So, learning how to do it makes our tasks easy. You can consider the below example to know what we are going to do.

Input:  array[] = {1, 2, 3}/before rotation                    
Output: array[] = {3, 1, 2}/after rotation

Steps for Cyclically rotate an array by one in Python

For cyclic rotation, the last element of the array should come to index zero shifting every element right side by one index (i.e elements at first index is to be moved the second index ).

Steps to do it :

  • Take array as input.
  • Once input is taken pass the array to the method rotate where we rotate an array by one in a cyclic manner.
  • For rotating array, we will store the last element array in a temporary variable then each element is shifted to the right by one index and at last value stored in the temporary variable is copied to the array at index zero.
  • The modified array is returned to the main method and printed.
def rotate(a, n): 
    x = a[n - 1] 
    for i in range(n - 1, 0, -1): 
        a[i] = a[i - 1]; 
    a[0] = x; 

a= [1, 2, 3] 
n = len(a) 
print("Input array is") 
rotate(a, n) 
print("Rotated array is") 
Input array is
[1, 2, 3]
Rotated array is
[3, 1, 2]

Time complexity: O(n)

Space complexity: O(1)


Also, visit:


Leave a Reply

Your email address will not be published. Required fields are marked *