Circular Array Rotation

Parag Naik
2 min readFeb 10, 2021

John Watson knows of an operation called a right circular rotation on an array of integers. One rotation operation moves the last array element to the first position and shifts all remaining elements right one. To test Sherlock’s abilities, Watson provides Sherlock with an array of integers. Sherlock is to perform the rotation operation a number of times then determine the value of the element at a given position. For each array, perform a number of right circular rotations and return the values of the elements at the given indices.

Photo by Markus Spiske on Unsplash

Solution-
In this hackerrank problem we are given an list “a” where we need to perform right rotation for “k” number of time i.e the last element in the list we take the first place and each element will shift to right side. Lets move towards the code we will declare an empty list say “lst” and then run a for loop for “k+1” iteration first we will in use insert function of list and insert the last element of the list at first and using the pop operation we will remove the last element which previous we have inserted at the start of the list. This iteration will run for “k” steps.

def circularArrayRotation(a, k, queries):
lst=[]
for i in range(1,k+1):
a.insert(0,a[-1])
a.pop(len(a)-1)
for j in queries:
lst.append(a[j])
return lst

After we have rotated the array/list “k” times we will use a for loop to print the element as per index number specified in “queries“ and append the values in empty list “lst”.

Conclusion:-
Keep learning and keep moving forward…(cheers:-PN)

--

--