Professional Documents
Culture Documents
Read
Discuss
Courses @Sale
Practice
Video
Given a list and an integer n, write a Python program to right rotate the list by n
position.
Examples :
Explanation: We get output list after right rotating (clockwise) given list by 2.
Approach #1 : Traverse the first list one by one and then put the elements at
required places in a second list.
● Python3
return output_list
# Driver Code
rotate_num = 3
list_1 = [1, 2, 3, 4, 5, 6]
print(rightRotate(list_1, rotate_num))
Output
[4, 5, 6, 1, 2, 3]
● Python3
list_1 = [1, 2, 3, 4, 5, 6]
list_1 = (list_1[len(list_1) -
n:len(list_1)]
+ list_1[0:len(list_1)
- n])
print(list_1)
Output
[4, 5, 6, 1, 2, 3]
Approach #3 : In the above method, last n elements of list_1 was taken and
then remaining elements of list_1. Another way is without using len() method.
● Python
list_1 = [1, 2, 3, 4, 5, 6]
if n>len(list_1):
n = int(n%len(list_1))
list_1 = (list_1[-n:] +
list_1[:-n])
print(list_1)
Output
[4, 5, 6, 1, 2, 3]
Note : list_1[:] will return the whole list as the blank space on left of slicing
operator refers to start of list i.e 0 and blank space on right refers to ending
position of list.
Approach 4: One additional approach that could be used to right rotate a list by
n positions is to use the collections.deque module. This module provides a
doubly-linked list that supports fast insertion and deletion at both ends of the list,
as well as fast rotating operations.
To right rotate a list by n positions, you can use the rotate() method of the deque
object. This method rotates the elements of the list by the specified number of
positions to the right. For example:
● Python3
Output
[4, 5, 6, 1, 2, 3]
The Auxiliary space complexity of the code is also O(n), because it involves
creating a new deque and a new list, both of which have the same size as the
input list.