Array Rotation:
It is the process of shifting elements of the array. There are two types of array rotations:
- Left Rotate
- Right Rotate
Left Rotate will shift all elements to left by one index and place the first index element to the last index.
Right Rotate will shift all elements to right by one index and place the last index element to the first index.
Here, we will take the array as input from the user and then the number of rotations to be done. We need to create a program in python to left rotate the elements of the array.
There can be multiple ways to rotate an array in python. Let's discuss them here,
Method 1: By rotating the array by one, R times
One rotation can be done by storing the first element, shifting all rest elements by one and then storing the first element to the last position.
We will repeat these steps R times to perform the task.
Algorithm:
- Get the array from the user.
- Repeat steps 3 to 5, R times.
- Initialize firstEle = arr[0].
- Loop from 0 to n-1
- Initialise arr[n] = firstEle.
- Return the array.
Program to rotate the array R times
Output:
Method 2: Using an extra array to store elements
In this method, we will use an extra array of size R, to store the elements for rotation. We will store the elements in an extra array and then shift every element's R places left. Then put the elements of the array after the last element of after shift.
Algorithm:
Program to rotate array using an extra array
Output:
Method 3: Using inbuilt slicing on list
The list slice can directly perform the task as we can slice the array from any index into half and use the sliced part as an array.
Program to rotate array using list slicing
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer